[英]WordPress show related posts based on taxonomy term
Below I have this code in single-courses.php which is currently displaying all the the courses.下面我在 single-courses.php 中有此代码,当前显示所有课程。 The goal is to show only related courses based on that courses' taxonomy term (category).
目标是仅显示基于该课程的分类术语(类别)的相关课程。 Help please.
请帮忙。
<?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(); ?>
i found a solution literally after i posted this question, sorry- but this is what worked for me.在我发布这个问题后,我确实找到了一个解决方案,对不起 - 但这对我有用。
<?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();
}?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.