So, here is the first code which shows the category of a post(or product).

 <?php echo $product->get_categories( ', ', '<span class="posted_in">' . _n( '', '', $cat_count, 'woocommerce' ) . ' ', '.</span>' ); ?>

Now second one is another code which uses category that is inputted by the users to display the posts(or products) of that particular category.

if (!empty($category))
            $category = str_replace('-1', implode(',', $categories) , $category);
            $query_args['tax_query'][] = array(
                'taxonomy' => 'product_cat',
                'field' => 'id',
                'terms' => explode(',', $category) ,
                'operator' => 'IN'

For example, if Demo-cat category is inputted by the user in the second code, then all the posts under this Demo-cat category will be displayed.

Now, here is what I am trying to achieve.

Instead of using the user inputted category, I want to show posts from current post's category.

Here is what I mean by it.

For example, let say you are viewing a post (Post title: Demo content, Post category: demo-cat).

In the post, the first code will display the category of the current post (demo-cat), I want to directly use this category in the second code to show other posts (same category) without having the user category input.

How can I somehow combine these two codes so that currently viewing post page's category will be used in the second code in order to show that particular categories' posts?

  • You are looking for related posts by terms on a single post. I have done a couple of these already on the site :-) – Pieter Goosen May 15 '15 at 7:41
  • You can use the same approach as I have described here – Pieter Goosen May 15 '15 at 7:43
  • Sweet. I will take a look at the link. Thanks Pieter! =) – Steve Kim May 15 '15 at 7:44

Your Answer

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

Browse other questions tagged or ask your own question.