简体   繁体   中英

WordPress custom post types: how to show in tag archives (tag.php)

I allow tags on my custom post types like this:

'taxonomies' => array('post_tag'),

My tag.php looks like this:

<h1><?php single_cat_title(''); ?></h1>

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

<h3><?php the_title(); ?></h3>

<?php endwhile; ?>

However, this is only showing posts with tags from the default post type and not my custom posts types.

I have tried adding the function found here: https://wordpress.stackexchange.com/questions/203239/tag-php-not-displaying-posts-with-the-tag/203241

But the only effect this has is now no posts are showing on the archive.

You must create a custom taxonomy for your custom post type inside the same function you used to create your custom post type.

"product_cat" it's the ID of your custom taxonomy (ie use it in WP_Query) and "array('products') it's the post type ID.


register_taxonomy('product_cat', array('products'), array(
            'hierarchical' => false, // Notice that this one is set to "false".
            'label' => 'Categorias de Produtos', // Sets the name in WordPress backoffice
            'singular_label' => 'Categoria do Produto',
            'rewrite' => array('slug' => 'categoria-producto', 'with_front' => false), // Defines it's URL.
        )
    );

    register_taxonomy_for_object_type('product_cat', 'products');

This will create a tag-like taxonomy for your custom post type

You also need to change this line

"taxonomies" => array("product_cat"),

To the ID of your custom taxonomy or else it won't show up.

Edit: Out of curiosity, setting the "hierarchical" value for "true" will create a category-like taxonomy.

I solved this by editing the function linked in my question to this:

function tag_filter($query) {
  if ( !is_admin() ) {
    if ($query->is_tag) {
      $query->set('post_type', array( 'custom_post_type', ));
    }
  }
}
add_action('pre_get_posts','tag_filter');

What I had to do was remove the check for main query and now all custom posts show on tag archive page using tag.php.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM