简体   繁体   中英

Get the current page custom taxonomy use to query custom post type

So far I have a custom taxonomy that is registered called position that is associated with a specific page as well a custom post type called People . I also have a page that has the custom taxonomy set to use the position taxonomy as well.

What I am trying to do is get it so that I can query the custom post type of People to show a list of entries with the custom taxonomy that is set on the page as well as the post type.

For example, the taxonomy of position has some items assigned to it, eg - Sales, Accounting, etc. I have some entries for the custom post type of People eg - John, Mary, Sam, etc. I have John and Mary set to use the taxonomy of Sales , in this case.

On the page of Sales, I have it set to use the custom position taxonomy of Sales .

What I'm trying to get is get the custom taxonomy of position on the Sales template page which should return the name and/or slug of Sales and then take that info and pass it into a query to check against the People custom post type and pull the associated people from that custom taxonomy. In this case, on the Sales page it should be able to pull the two people of John and Mary.

So far I have this on the Sales template page:

<?php $tax = get_terms( array( 'taxonomy' => 'position' ) ); ?>

That gives me the array of the terms but how do I get the name of the associated taxonomy name that is set on the page and then pass that to a query to get the people?

Looks like if I use get_terms it gives me everything and just need the one set taxonomy that is for that particular page, assign that to a variable and then use it for a query like this:

<?php $args = array( 'post_type' => 'people', 'taxonomy' => $tax);
$loop = new WP_Query( $args ); ?>

Ok so I got it figured out eventually.

In order to make this work you'd need to get the current post ID from the page, pass that through get_the_terms and then construct a query to query the custom post type with tax_query and then pass that into the tax_query array:

<?php
            $id = get_post($post->ID);
            $tax = get_the_terms($id, 'position');
            $args = array(
              'post_type' => 'people',
              'tax_query' => array(
                array(
                  'taxonomy' => 'position',
                  'field'    => 'slug',
                  'terms'    => $tax[0]->slug,
                ),
              ),
            );
            $loop = new WP_Query( $args );
            ?>

That will cross reference the custom taxonomy between the current page and the custom post types and will get those post types that are assigned with the specific taxonomy (in this case, Sales).

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM