wp query – Display related CPT with custom taxonomy

Question

I have two custom post types: “storefront_location” and “services”

These are linked by a custom taxonomy “location”

I am building a post template for “storefront_location” and would like to display a listing of the “services” posts associated with any given storefront.

What I’m trying to achieve:

A “storefront-location” post, London, is categorized with “london” (“location” taxonomy).
I would like that London “storefront-location” post to display all “services” which are also categorized with “london” (“location” taxonomy). Users could then click on each service to read about it, since these are post types.

I’m trying to get the taxonomy information of the current post (London) and use tax-query to find all the services that share the same taxonomy with that specific London post.

Note: this is for a WP_query filter in Elementor, so the extra code for the Elementor query is from their tutorial here.

I’m fairly new to this, so there might be a newbie problem here. I’ve been trying to figure this out from other code examples here on stack exchange. I’d appreciate any help!

add_action( 'elementor/query/my_filter', function( $query ) {
//get the storefront-location post's location
   $custom_terms = wp_get_post_terms($post->ID, 'location');

if( $custom_terms ){

    //hold tax query parameters
    $tax_query = array();


    // loop through locations and build a tax query
    foreach( $custom_terms as $custom_term ) {

        $tax_query[] = array(
            'taxonomy' => 'location',
            'field' => 'slug',
            'terms' => $custom_term->slug,
        );

    }

    // put all the WP_Query args together
    $args = array( 'post_type' => 'services',
                    'posts_per_page' => -1,
                    'tax_query' => $tax_query );

    // finally run the query
    $loop = new WP_Query($args);

    if( $loop->have_posts() ) {

        while( $loop->have_posts() ) : $loop->the_post(); ?>

        <div class="listing-title"><?php the_title(); ?></div>     
        <?php endwhile;
    }

    wp_reset_query();

}
});

0
srack 1 week 2021-07-19T13:39:41-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse