欢迎光临
我们一直在努力

WordPress 获取自定义文章类型的相关文章

自定义分类的相关文章
所谓“自定义分类”是指非默认的 category 这个分类法。以下是代码样例:

<?php
/**
* WordPress 获取自定义文章类型的相关文章(自定义分类)
* https://www.wpdaxue.com/related-custom-post-type-taxonomy.html
*/
// 获取自定义文章类型的分类项目
$custom_taxterms = wp_get_object_terms( $post->ID,'your_taxonomy', array('fields' => 'ids') );
// 参数
$args = array(
'post_type' => 'YOUR_CUSTOM_POST_TYPE',// 文章类型
'post_status' => 'publish',
'posts_per_page' => 3, // 文章数量
'orderby' => 'rand', // 随机排序
'tax_query' => array(
array(
'taxonomy' => 'your_taxonomy', // 分类法
'field' => 'id',
'terms' => $custom_taxterms
)
),
'post__not_in' => array ($post->ID), // 排除当前文章
);
$related_items = new WP_Query( $args );
// 查询循环
if ($related_items->have_posts()) :
echo '<h3 class="related-posts-title">Related Posts</h3><ul>';
while ( $related_items->have_posts() ) : $related_items->the_post();
?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php
endwhile;
echo '</ul>';
endif;
// 重置文章数据
wp_reset_postdata();

你需要根据自己的实际,修改如下参数:

第 7 行和第 16 行:修改 your_taxonomy 为你的自定义分类法

11行:’YOUR_CUSTOM_POST_TYPE’ 你需要修改为你的自定义文章类型

12行: 修改文章数量

还可以修改 26、29、32行的代码来输出自己想要的内容,比如添加缩略图,以及更多文章meta信息等。

参考资料:

Get Related Posts For Custom Post Type by Custom Taxonomy

Get Related Posts For Custom Post Type By Category

窗外天空
关注公众号『窗外天空』

获取更多建站运营运维新知!
互联网创业、前沿技术......

赞(0) 打赏
文章名称:《WordPress 获取自定义文章类型的相关文章》
文章链接:https://www.nixonli.com/136.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。

评论 抢沙发

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫

微信扫一扫