0

I have created a custom post type named 'portfolio' and assigned the default 'post_tag' taxonomy to it.

In single-portfolio.php template I'm using the following code to view each post's tags:

echo get_the_tag_list('<p class="tag_list"><strong>Tags: </strong>',', ','</p>');

The problem is that the link of each tag is not correct and finally redirects into a 404 page. The link that get_the_tag_list() returns looks like:

http://www.mywebsite.com/?tag=web-design

but in order to work properly it should be something like:

http://www.mywebsite.com/?tag=web-design&post_type=portfolio

Any suggestions on how to fix this??

Note: I have also tried get_the_term_list() function but it works the same way...

  • Check this link. – Nilambar Sep 8 '14 at 9:02
  • 1
    You cannot name your custom taxonomy post_tag. It is a reserved name – Pieter Goosen Sep 8 '14 at 9:06
  • @Nilambar thanks for the link but I don't want to use permalinks, I'm using the default link structure. – ktsixit Sep 8 '14 at 9:08
  • @PieterGoosen I have registered the tag taxonomy on Portfolio using register_taxonomy_for_object_type( 'post_tag', 'portfolio' ); – ktsixit Sep 8 '14 at 9:19
  • Your info is wrong then and confusing :-). I have corrected your question – Pieter Goosen Sep 8 '14 at 9:25
2

The reason for your problem is that, by default, custom post types are excluded from the main query. As there are no "normal" posts assigned to the specific tag, you get a 404 page when trying to view the specific tag's page

In order for this to work, you'll need to add your custom post type to the main query before it executes. To accomplish this, you'll need to use pre_get_posts. If you just want to target the tag archive page, you can make use of the conditional tag is_tag()

The following code in your functions.php will work

function custom_post_type_tags( $query ) {
    if ( !is_admin() && $query->is_tag() && $query->is_main_query() ) {
        $query->set( 'post_type', array( 'post', 'portfolio' ) );
    }
}
add_action( 'pre_get_posts', 'custom_post_type_tags' );

EDIT

If you need to display your custom post type in all templates, you can just remove the is_tag() condition

function custom_post_type_tags( $query ) {
    if ( !is_admin() && $query->is_main_query() ) {
        $query->set( 'post_type', array( 'post', 'portfolio' ) );
    }
}
add_action( 'pre_get_posts', 'custom_post_type_tags' );
  • 1
    Please recheck my answer. Code had a synatx error. :-) – Pieter Goosen Sep 8 '14 at 10:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.