The situation is this: I have created a custom post type which works perfectly, now I want to create a specific archive page template for the taxonomies of this post type.
I duplicated the archive.php
page of my theme (schema by MTS) but it doesn’t work in this case.
Here the code:
<?php
$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ), get_query_var( 'count' ) );
echo $term->name;
echo ' has nr elements: ';
echo $term->count;
?>
<div id="page">
<div class="<?php mts_article_class(); ?>">
<div id="content_box">
<h1 class="postsby">
<span><?php echo the_archive_title(); ?></span>
</h1>
<?php $j = 0; if (have_posts()) : while (have_posts()) : the_post(); ?>
<article class="latestPost excerpt <?php echo (++$j % 3 == 0) ? 'last' : ''; ?>">
<?php mts_archive_post(); ?>
</article><!--.post excerpt-->
<?php endwhile; else: echo 'nothing'; endif; ?>
<?php if ( $j !== 0 ) { // No pagination if there is no posts ?>
<?php mts_pagination(); ?>
<?php } ?>
</div>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
The strange aspect is that the code print “nothing” because the function have_posts()
return false but the $term->count
is 3
.
Can you help me please? Thank you very much in advance!
3 Answers
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'
) );
}
}