How to check if wp_query results found any custom post_type?

Viewed 215

In my WordPress v5.8.1, I have the below query in taxonomy.php to get the list of posts.

$args = array(
 'post_type' => array('song', 'dance'),
 'post_status' => 'publish',
 'posts_per_page' => 10,
 );
 query_posts($args);

The query return posts from both post_type's.

I would like to create a menu in the same page, where I want to check if the query results has found posts from a specific post_type. The menu looks something like this.

  • This taxonomy has posts from Song, Dance (if found posts from both post_type's), or

  • This taxonomy has posts from Song (if found posts from Song post_type only)

Have tried the below within the loop:

    $song_count = wp_posts_count('song')->found_posts;
    $dance_count = wp_posts_count('dance')->found_posts;
     if ($song_count=>0 {
     /** code goes here **/
    }

Above is returning the count from entire WordPress, not just from current taxonomy.

1 Answers

You can stock result in variable, but did I understand the question correctly?

$args = array(
    'post_type' => array('song', 'dance'),

    // or 'post_type' => get_post_type($post->ID),
    // conditions are no longer necessary

    'post_status' => 'publish',
    'posts_per_page' => 10,
);
$results = query_posts($args);

if($results) {
    $count = 0;
    $current_post_type = get_post_type($post->ID);
    $current_post_type_name = get_post_type_object(get_post_type())->labels->singular_name); // ajust with 2 variables for multiple results
    foreach($results as $result) {
        // if request is in a single custom post  
        if($result->post_type == $current_post_type) {
            $count++;
        }       
    }
    if($count > 0) {
        echo $count . $current_post_type_name;
    }
}
else {
    // no results
}
Related