Home » Jquery » php – WordPress – Retrieve all Posts by 'post_type' then filter by taxonomy

php – WordPress – Retrieve all Posts by 'post_type' then filter by taxonomy

Posted by: admin February 22, 2020 Leave a comment

Questions:

I have a WordPress installation with ACF (Advanced Custom Fields) installed. I created the Class post type and each Class has it’s on Location value.
How can I retrieve every Class and get the location I have chosen for that Class?
I’m currently using this function to retrieve the name of the ‘Programs’:

<pre>
    $args = array(
        'post_type' => 'class',
        'posts_per_page' => -1,
    );
    $query = new WP_Query($args);
    if ($query->have_posts() ) : 
        while ( $query->have_posts() ) : $query->the_post();
            echo get_the_ID();
            echo get_the_title();
        endwhile;
    endif;
</pre>

I’m trying to populate a dropdown list ‘Location’ which filters the next dropdown with the classes available for that location.
Any help or advice would be greatly appreciated. Thanks

How to&Answer:

Not sure if this is what you’re asking for, but here’s how you can pull each posts locations inside of your query loop. Just update locations in the get_the_terms function with what you named the taxonomy.

if ($query->have_posts() ) : 
    while ( $query->have_posts() ) : $query->the_post();
        $locations = get_the_terms($post->ID, 'locations');

        echo get_the_ID();
        echo get_the_title();

        foreach ($locations as $location) :
          echo '<p>' . $location->name . '</p>';
        endforeach;
    endwhile;
endif;

Answer:

I managed to find the solution using the previous answer from trev.
Here is the solution I implemented:

<pre>
$args = array(
    'post_type' => 'class',
    'posts_per_page' => -1,
);
$query = new WP_Query($args);
$classArray = [];
if ($query->have_posts() ) {
    while ( $query->have_posts() ) : $query->the_post();
        $id = get_the_ID();
        $location = wp_get_post_terms($id, 'location');
        $location = $location[0]->name;
        $classArray[] = array(
            'id'        => get_the_ID(),
            'name'  => html_entity_decode(get_the_title()),
            'location'  => $location
        );

    endwhile;
    wp_reset_postdata();
}
</pre>

This allowed me to create an array containing the Class ID, Name of the Class and the location associated with it. Thanks for your advice.