简体   繁体   中英

Show related posts by taxonomy Wordpress

I am trying to show related posts by taxonomy in single post page on Wordpress. I've used the following code to show posts in the same category, but not the same custom taxonomy. The custom taxonomy I need to use is product_cat

<?php
global $post;
$categories = get_the_category();
$category = $categories[0];
$cat_ID = $category->cat_ID;
$loop = new WP_Query( array( 'post_type' => 'product','post__not_in' => array($post->ID), 'category' => $cat_ID ) ); ?>

<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>

<?php the_title( '<h2 class="entry-title"><a href="' . get_permalink() . '" title="' . the_title_attribute( 'echo=0' ) . '" rel="bookmark">', '</a></h2>' ); ?>

<?php endwhile; ?>

How can I adjust the current code?

Did you tried adding the following argument to your WP_Query array of arguments?

  'tax_query' => array(array('taxonomy' => 'product_cat'))

The code will look like this (of course after removing the category parameter):

<?php
global $post;

$loop = new WP_Query( array( 'post_type' => 'product','post__not_in' => array($post->ID),  'tax_query' => array(array('taxonomy' => 'product_cat'))) ); ?>

<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>

<?php the_title( '<h2 class="entry-title"><a href="' . get_permalink() . '" title="' . the_title_attribute( 'echo=0' ) . '" rel="bookmark">', '</a></h2>' ); ?>

<?php endwhile; ?>

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