[英]Related posts category in wordpress (taxonomy)
如何使用此代码仅显示“按类别分类的相关帖子”? 这段代码在“ single.php”里面,我没有stackoverflow但找不到解决方案。 谁能帮我?
<?php
$postsPerPageq = 5;
$allargw = array(
'post_type' => 'audioplayer',
'posts_per_page' => $postsPerPageq,
'orderby' => 'title',
'order' => 'DESC',
'tax_query' => array(
array(
'taxonomy' => 'audiotop',
'field' => 'slug',
'terms' => 'top-audio'
)
)
);
$topaudio = new WP_Query($allargw);
while ( $topaudio->have_posts() ) : $topaudio->the_post();
?>
<h3><a href="<?php the_permalink(); ?>"><?php the_title();?></a></h3>
<?php endwhile; wp_reset_postdata();?>
首先,您需要使用此功能来获取当前的职位条款
get_the_terms ( get_the_id(), 'your_custom_taxonomy' );
那么您就可以在WP_Query中获取tax_query的条款。
$postsPerPageq = 5;
$terms_slugs = array();
//get the current post terms slug
$terms = get_the_terms( get_the_id(), 'audiotop' );
foreach ( $terms as $term) {
$terms_slugs[] = $term->slug;
}
//WP_Query args
$allargw = array(
'post_type' => 'audioplayer',
'posts_per_page' => $postsPerPageq,
'orderby' => 'title',
'order' => 'DESC',
'tax_query' => array(
array(
'taxonomy' => 'audiotop',
'field' => 'slug',
'terms' => $terms_slugs,
)
)
);
我希望它能解决您的问题。
在您的allargw数组值中添加类别名称。
<?php
$postsPerPageq = 5;
$allargw = array(
'post_type' => 'audioplayer',
'posts_per_page' => $postsPerPageq,
'category_name'=>'Your category name',
'orderby' => 'title',
'order' => 'DESC',
'tax_query' => array(
array(
'taxonomy' => 'audiotop',
'field' => 'slug',
'terms' => 'top-audio'
)
)
);
$topaudio = new WP_Query($allargw);
while ( $topaudio->have_posts() ) : $topaudio->the_post();
?>
<h3><a href="<?php the_permalink(); ?>"><?php the_title();?></a></h3>
希望这对您有帮助!
更新的答案:
如果要自动添加类别,请像这样使用。
wp_set_object_terms( 'your_post_id', 'your_category_name', 'your_taxonomy_name');
你可以试试看
如果要按简单帖子类别检索帖子,请检查以下代码:
<?php
$category = get_the_category($post->ID);
$cat_id = $category[0]->term_id;
$postsPerPageq = 5;
$allargw = array(
'post_type' => 'audioplayer',
'posts_per_page' => $postsPerPageq,
'orderby' => 'title',
'order' => 'DESC',
'cat' => $cat_id
);
$topaudio = new WP_Query($allargw);
while ( $topaudio->have_posts() ) : $topaudio->the_post(); ?>
<h3><a href="<?php the_permalink(); ?>"><?php the_title();?></a></h3>
<?php endwhile; wp_reset_postdata();?>
否则,如果要按自定义分类检索帖子,请检查以下代码:
<?php
$term_list = wp_get_post_terms($post->ID, 'audiotop', array("fields" => "all"));
$term_id = $term_list[0]->term_id ;
$postsPerPageq = 5;
$allargw = array(
'post_type' => 'audioplayer',
'posts_per_page' => $postsPerPageq,
'orderby' => 'title',
'order' => 'DESC',
'tax_query' => array(
array(
'taxonomy' => 'audiotop',
'field' => 'id',
'terms' => $term_id
)
)
);
$topaudio = new WP_Query($allargw);
while ( $topaudio->have_posts() ) : $topaudio->the_post(); ?>
<h3><a href="<?php the_permalink(); ?>"><?php the_title();?></a></h3>
<?php endwhile; wp_reset_postdata();?>
希望这个能对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.