首页 > WordPress学习 > WordPress相关推荐文章根据tag标签获取 以及用分类文章填充文章数量不足

WordPress相关推荐文章根据tag标签获取 以及用分类文章填充文章数量不足

时间:2023年1月13日 分类:WordPress学习 浏览量:245

我们在制作文章模板时,需要展示当前文章的相关推荐文章,那么这个该怎么实现?

这里提供一种,优先获取tag标签,并依据tag标签获取关联文章的方法,如果数量不足,会获取当前分类的其他文章来填补

        <?php
        $post_tags=wp_get_post_tags($post->ID); //如果存在tag标签,列出tag相关文章
        $pos=1;
        if($post_tags) {
        foreach($post_tags as $tag) $tag_list[] .= $tag->term_id;
        $args = array(
        'tag__in' => $tag_list,
        'category__not_in' => array(), // 不包括的分类ID
        'post__not_in' => array($post->ID), //排除当前文章ID
        'showposts' => 12, // 显示相关文章数量
        'caller_get_posts' => 1,
        'orderby' => 'date',
        );
        $newpost = new WP_Query($args);
        if ( $newpost -> have_posts() ): while ( $newpost -> have_posts() &&$pos<=12) : $newpost ->the_post(); update_post_caches($posts); ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        </li>
        <?php $pos++;endwhile;wp_reset_query();endif; ?>
        <?php } //tag文章获取结束 ?>
        <?php if($pos<=12): //如果tag相关文章少于12篇,那么继续以分类作为相关因素列出相关文章
        $cats = wp_get_post_categories($post->ID);
        if($cats){
        $cat = get_category( $cats[0] );
        $first_cat = $cat->cat_ID;
        $args = array(
        'category__in' => array($first_cat),
        'post__not_in' => array($post->ID),
        'showposts' => 12,
        'caller_get_posts' => 1,
        'orderby' => 'rand',
        );
        $newpost = new WP_Query($args);
        if ( $newpost -> have_posts() ): while ( $newpost -> have_posts() && $pos<=12) : $newpost ->the_post(); update_post_caches($posts); ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        </li>
        <?php $pos++;endwhile;wp_reset_query();endif; ?>
        <?php } endif; //分类文章获取结束 ?>
        <?php if($pos<=12){ //如果上面两种相关都还不够12篇文章,再随机挑几篇凑成12篇 ?>
        <?php 
        $args = array(
        'showposts' => 12,
        'orderby' => 'rand',
        );
        $newpost = new WP_Query($args);
        if ( $newpost -> have_posts() ): while ( $newpost -> have_posts() && $pos<=12) : $newpost ->the_post(); ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        </li>
        <?php $pos++;endwhile;endif; wp_reset_query();?>
        <?php } ?>

以上代码里,调用部分,可以依据各自站点进行修改,包括调用文章数量等,都可以根据实际情况进行调整

版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权

文章名称:WordPress相关推荐文章根据tag标签获取 以及用分类文章填充文章数量不足

文章链接:https://news.yynnw.com/145.html

该作品系作者结合个人学习经验及互联网相关知识整合。如若侵权请通过投诉通道提交信息,我们将按照规定及时处理。

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

微信扫一扫打赏

标签:

最新文章