Custom post type tag archives don’t work for basic loop?

The question:

I have registered a custom post type with the right parameters. By that I mean I have added 'taxonomies' => array('post_tag','category'),

I have also tried using register_taxonomy_for_object_type('post_tag', 'custom-post-type-name');

I have a custom function in my functions.php to load a basic loop using a conditional, along the lines of.

function child_maybe_do_grid_loop() {    
if( is_tag() || is_category() || is_archive {
require(CHILD_DIR.'/custom-tag.php');
 }
}

The content of custom-tag.php is just a very basic loop

<?php if (have_posts()) : ?>
 <?php while (have_posts()) : the_post(); ?> 
   <?php the_permalink(); ?>" title="<?php the_title(); ?> 
 <?php endwhile; ?>    
<?php else : ?>
<h2 class="center">Not Found</h2>
<?php endif; ?>

This works fine for regular posts/page tags but for a custom post type tags I get “Not Found”.

Any ideas? I assumed a regular simple loop should work with custom posts type tag archives or do I need to put some extra conditionals/query’s in there?

** Update toscho’s comment made me turn on debugging and in comparison to a working tag page made through a default post, the debug for custom post tag is exactly the same.

I even get count => 2 to show up as I incrementally add more custom posts to the same tag, yet the page refuses to return anything, I am at a loss.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Down the rabbit hole….. I found a fix.

From this post Custom Post Type Archives by Date and Taxonomy

Which let me to this trac ticket http://core.trac.wordpress.org/ticket/14589

and the following

function post_type_tags_fix($request) {
    if ( isset($request['tag']) && !isset($request['post_type']) )
    $request['post_type'] = 'any';
    return $request;
} 
add_filter('request', 'post_type_tags_fix');

Maybe this didn’t make it into 3.1?

Method 2

You need to run the loop before the conditional statement.

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

<?php if( is_tag() || is_category() || is_archive { ?>

<?php the_permalink(); ?>" title="<?php the_title(); ?> 

<? } else { ?>

//do something else

} ?>

<?php endwhile; ?>    
<?php else : ?>
<h2 class="center">Not Found</h2>
<?php endif; ?>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment