have_posts() return false but count says “3”

I had same problem.

According to documentation:

The hierarchy for a custom taxonomy is listed below:

taxonomy-{taxonomy}-{term}.php
taxonomy-{taxonomy}.php
taxonomy.php
archive.php
index.php

So, it doesn’t matter witch template file you are using, all of them will generate same issue.

When I put in the beginning of template file code var_dump($wp_query);, i found this:

public 'request' => string 'SELECT SQL_CALC_FOUND_ROWS  wp_posts.ID FROM wp_posts  LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) WHERE 1=1  AND ( 
  wp_term_relationships.term_taxonomy_id IN (20)
) AND wp_posts.post_type IN ('post', 'page', 'attachment') AND (wp_posts.post_status="publish" OR wp_posts.post_author = 1 AND wp_posts.post_status="private") GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC LIMIT 0, 10' (length=433)
  public 'posts' =>

Important part in this query is wp_posts.post_type IN ('post', 'page', 'attachment').

Problem occur because there is no your custom post_type in this array ('post', 'page', 'attachment').

I don’t know why it’s happen, but it’s possible to fix it using pre_get_posts hook:

add_filter('pre_get_posts', 'add_custom_post_type_to_query');
function add_custom_post_type_to_query($query) {
    // We do not want unintended consequences.
    if ( is_admin() || ! $query->is_main_query() ) {
        return;    
    }

    // Check if custom taxonomy is being viewed
    if( is_tax() && empty( $query->query_vars['suppress_filters'] ) )         
    {
        $query->set( 'post_type', array( 
            'post',
            'page',
            'my_custom_post_type'
        ) );
    }
}

Leave a Comment

tech