Syahnur Nizam
Syahnur Nizam

Reputation: 91

WordPress URL for showing post by both category and tag

How can I show all posts with a specific category foo and a specific tag bar by using URL?

Example: site.com/category/foo/tag/bar

or

Example: site.com/posts?category={category-id}&tag={tag-id}

Upvotes: 3

Views: 4746

Answers (2)

Scott Stoll
Scott Stoll

Reputation: 41

The structure looks like this, but depending on your permalink structure.

/category/category-name/?tag=tag-name

Upvotes: 3

Raunak Gupta
Raunak Gupta

Reputation: 10809

I don't know if there is a default feature for this or not but I have an idea as how to achieve it.

You can create a custom template for this and in that template get the query string by get_query_var() and then use WP_Query cat and tag argument to fetch your posts belonging to that cat/tag.

Here is a sample working code:

$cat_id = get_query_var('category');
$tag_id = get_query_var('tag');
$args = [
    //...
    //...
    'post_type' => 'post', //<-- Replace it with your custom post_type
    'post_status' => 'publish',
    'tag_id' => $tag_id, //replace tag_id with tag if you are passing tag slug
    'cat ' => $cat_id //replace cat with category_name if your are passing category slug
    //...
    //...
];

// The Query
$query = new WP_Query($args);
if (!empty($query->posts))
{
    //print_r($query->posts);
    foreach ($query->posts as $post)
    {
        //Your filtered post
    }
}

Hope this helps!

Upvotes: 2

Related Questions