WordPress 根据分类术语显示相关帖子
Posted
技术标签:
【中文标题】WordPress 根据分类术语显示相关帖子【英文标题】:WordPress show related posts based on taxonomy term 【发布时间】:2022-01-06 19:14:53 【问题描述】:下面我在 single-courses.php 中有这段代码,它当前正在显示所有课程。目标是仅显示基于该课程的分类术语(类别)的相关课程。请帮忙。
<?php
$related = get_posts( array(
'taxonomy' => 'course_category',
'post_type' => 'courses',
'numberposts' => -1
)
);
if( $related ) foreach( $related as $post )
setup_postdata($post); ?>
<div class="row next-chapter-list" onclick="location.href='<?php the_permalink();?>';">
<div class="col-md-10 col-9 valign text-left">
<?php the_title(); ?>
</div>
<div class="col-md-2 col-3 valign text-right">
<i class="bi bi-play-fill"></i>
</div>
</div>
<?php
wp_reset_postdata(); ?>
【问题讨论】:
【参考方案1】:在我发布这个问题后,我确实找到了一个解决方案,抱歉-但这对我有用。
<?php
//get the post's venues
$custom_terms = wp_get_post_terms($post->ID, 'course_category');
if( $custom_terms )
// going to hold our tax_query params
$tax_query = array();
// add the relation parameter (not sure if it causes trouble if only 1 term so what the heck)
if( count( $custom_terms > 1 ) )
$tax_query['relation'] = 'OR' ;
// loop through venus and build a tax query
foreach( $custom_terms as $custom_term )
$tax_query[] = array(
'taxonomy' => 'course_category',
'field' => 'slug',
'terms' => $custom_term->slug,
);
// put all the WP_Query args together
$args = array( 'post_type' => 'courses',
'posts_per_page' => 5,
'tax_query' => $tax_query );
// finally run the query
$loop = new WP_Query($args);
if( $loop->have_posts() )
while( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="row next-chapter-list" onclick="location.href='<?php the_permalink();?>';">
<div class="col-md-10 col-9 valign text-left">
<?php the_title(); ?>
</div>
<div class="col-md-2 col-3 valign text-right">
<i class="bi bi-play-fill"></i>
</div>
</div>
<?php
endwhile;
wp_reset_query();
?>
【讨论】:
以上是关于WordPress 根据分类术语显示相关帖子的主要内容,如果未能解决你的问题,请参考以下文章
php 使用show_on_cb根据分配了分类术语的帖子/页面显示/隐藏CMB字段