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

 4年前     1.1K  

文章目录

WordPress 的文章页面,我们都会推荐一些相关文章,区别于 WordPress  默认的文章类型“post”,自定义文章类型的相关文章实现方法有点不同。

效果演示

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

方法

所谓“自定义分类”是指非默认的 category 这个分类法。以下是代码,按照注释修改内容。

<?php
/**
 * 获取 WordPress 自定义文章类型的相关文章
 * https://www.iowen.cn/custom-article-related-content
 */
// 获取自定义文章类型的分类项目
$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">相关文章</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 为你的自定义分类法

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

11行: 修改需要显示的文章数量

显示样式和结构请修改 26、29、32行的代码,来输出自己想要的内容,比如添加缩略图,以及更多文章meta信息等。

版权声明:一为 发表于 4年前,共 1132 字。
转载请注明:获取 WordPress 自定义文章类型的相关文章 | 一为忆

您可能感兴趣的

1 条评论

  • avatar

    青云 ( VIP 1 )

    安徽
    回复

    :wink: 是个好文章呀!