0
votes

I have a Custom Post Type called 'references' with the taxonomy 'references-cats'. Parent and child terms are:

  • social media
  • corporate communications
  • events
  • competences
    • social media
    • events

Some of some of the Child Terms are identical with the Parent Terms. I would like to query all posts of 'social media' (but only the children of 'competences') – is there an exact way to do that?

<?php 

$tagz = get_the_title(); // single post title as we are on a single page

    query_posts(array( 
        'post_type' => 'references',
        'tax_query' => array(
            'relation' => 'AND',
            array (
                'taxonomy' => 'references-cats',
                'field' => 'slug',
                'terms' => $tagz, // single post title corresponds with term
            ),
            array(
                'taxonomy' => 'references-cats',
                'field' => 'slug',
                'terms' => 'competences',
                'operator' => 'IN'
            )
        ),
        'showposts' => 7
    ) ); 

?>
2

2 Answers

0
votes

Terms in WordPress have unique slugs, so it doesn't matter if you have 2 terms with the same names, they will have different slugs. So you don't need to query the references by both parent and child since you are anyway using the slug to make the tax query.

'tax_query' => array(
    array(
        'taxonomy' => 'references-cats',
        'field'    => 'slug',
        'terms'    => $slug
    )
)

The above piece of code is enough for the tax query, you should just use the proper slug for each taxonomy term in the $slug variable.

L.E.:

Matching your title with your term slug is not a good approach. You can achive what you want easily by creating a metabox on the page(with ACF of with custom code) where you select the category from which you want to display references on each specific page.

0
votes

Solution:

  1. Query for all posts with parent taxonomy. competences
  2. Then in while loop check if post have child taxonomy.

Example:

$args_query = array(
    'post_type' => array('references'),
    'posts_per_page' => -1,
    'tax_query' => array(
        array(
            'taxonomy' => 'references-cats',
            'field' => 'term_id',
            'terms' => array(PARENT-TAXONOMY-ID),
        ),
    ),
);

$query = new WP_Query( $args_query );

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        if (has_term($tagz, 'references-cats')) {
            // have $tags
        }
    }
}

wp_reset_postdata();

Also you can use below code instead of has_term()

if (is_object_in_term( $post->ID, $taxonomy, $term )) {
    // code
}