简体   繁体   English

按分类显示相关帖子Wordpress

[英]Show related posts by taxonomy Wordpress

I am trying to show related posts by taxonomy in single post page on Wordpress. 我正在尝试在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 我需要使用的自定义分类法是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? 您是否尝试将以下参数添加到WP_Query参数数组中?

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

The code will look like this (of course after removing the category parameter): 该代码将如下所示(当然,在删除category参数之后):

<?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; ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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