I have various products (custom post type) which already have categories but I have now I have added this line to be able to add tags to the products.
'taxonomies' => array('post_tag')
So, I have an industries section with various pages within that and for example one of them is called ‘Woodworking’. I have added the tag ‘Woodworking’ to various products and when someone visits /industry/woodworking I want those products to show up.
Is there an easy way to achieve this? I thought of perhaps using WP_Query
but not sure how to create that relationship between the page name and the product tags.
EDIT:
I have done this which seems to work but not sure if the right way to go about it?
<?php $page_title = get_the_title(); ?>
<?php
$tag_prods = new WP_Query(array(
'tag' => 'Woodworking',
'posts_per_page' => -1,
'post_type' => 'Products',
'order' => 'ASC'
));
?>
<?php if ($tag_prods->have_posts() ): while ($tag_prods->have_posts() ): $tag_prods->the_post(); ?>
<?php foreach(get_the_tags() as $tags): ?>
<?php if ($tags->name === $page_title): ?>
<p><?php the_title(); ?></p>
<?php endif; ?>
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
<?php endwhile; ?>
<?php endif; ?>
Just noticed that this only works with single words. As soon as a tag word has a space in it then it doesn’t pick it up.
1 Answer
I have done this which seems to work but not sure if the right way to
go about it?
Yes, you can create a custom Page template which displays posts in your custom post type, and use that template with those “industry” pages.
And if you want, you can create a single Page which will handle all the “industry” requests/URLs like /industry/woodworking
. And then you can use add_rewrite_rule()
to add a custom rewrite rule which redirects the requests to that Page.
Or you can also redirect them to the tag archives. Example:
add_action( 'init', function(){
add_rewrite_rule( '^industry/woodworking',
'index.php?tag=woodworking&post_type=Products',
'top' );
} );
Just noticed that this only works with single words. As soon as a tag
word has a space in it then it doesn’t pick it up.
As pointed in my comment, that’s because the tag
parameter expects one or more tag slugs and not names. Examples:
-
'tag' => 'tag-one, tag-two'
— correct. -
'tag' => 'Tag One, Tag Two'
— incorrect.
You can check the full parameters list here.