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

在 WordPress 的文章页面,一般我们都会推荐一些相关文章,对于WordPress 自带的文章类型“post”,可以根据参考下面的文章来实现:

WordPress添加相关文章功能(标题/缩略图样式)

WordPress相关文章插件:Yet Another Related Posts Plugin

WordPress相关文章插件:WordPress Related Posts

但如果是自定义文章类型(Custom Post type),要调用相关文章就需要修改查询参数了。如果你还不知道什么是自定义文章类型,请查看:WordPress 自定义文章类型 介绍及实例解说

下面分享两种情况下的调用方法,默认都是添加到主题的 single.php  或 single-custom_post_type.php 文件。

默认分类的相关文章

所谓“默认分类”是指自带的文章类型post的分类“category”。也就是在注册自定义文章类型时,你注册的分类法就是 category 的时候。以下是代码样例:

<?php
/**
 * WordPress 获取自定义文章类型的相关文章(默认分类)
 * https://www.wpdaxue.com/related-custom-post-type-taxonomy.html
 */
// 获取自定义文章类型的分类项目
$custom_taxterms = wp_get_object_terms( $post->ID,'category', 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' => 'category', // 分类法
        '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();
?>

你需要根据自己的需要,修改参数:

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

12行: 修改文章数量

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

自定义分类的相关文章

所谓“自定义分类”是指非默认的 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信息等。

参考资料:

来源:

https://www.wpdaxue.com/related-custom-post-type-taxonomy.html

微信公众号
手机浏览(小程序)
0
分享到:
没有账号? 忘记密码?