WordPress 首页第 X 篇文章后插播随机文章

zhijun(57)
Published in
#cn
Words
390
Reading
2 min
Listen
Play
9y

博客目前就是个自娱自乐的地方,没什么访问量,纯粹是折腾给自己看的。挂了些 VPS 的推荐链接,其实主要是 Bandwagon Host。那些纯粹是优惠信息的文章,默认不在首页显示。昨天突发奇想,让它们随机显示一篇在首页露露脸也好,说不定有需要的看上了呢?

wordpress-1863504_640.png

Image Credit:https://pixabay.com

于是就有了这篇文章。

需求:首页第二篇文章后随机显示一篇来自优惠信息分类的文章,更进一步,判断这个分类最近是否有新文章,有就显示最新的文章,没有才显示随机文章。

以前折腾过类似功能,现在弄起来不是很难。

WordPress The Loop 里面有个 $current_post 变量,可以取得当前文章的索引(序号)。『$current_post:(available during The Loop) Index of the post currently being displayed.』可以通过判断它的值,就可以实现将随机文章插入到第 X 篇文章后。

接着是判断最近(比如一周内)是否有新文章,这个也好实现。WordPress 3.7 版本后的 WP_Query 日期参数新增 date_query (array),通过这个参数,很方便就能获取指定分类指定时间内的文章。

下面是 index.php 实现参考代码:

<?php
    $paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;
    $args = array(
        'category__not_in' => 888,//排除分类id:888
        'paged' => $paged
    );
    $wp_query = new WP_Query($args);//主循环

    $week = date( 'W' );
    $year = date( 'Y' );

    $args_rand = array(
        'category__in'  => 888,//选择分类文章id:888
        'posts_per_page'  => 1,//每页显示一篇
        'orderby'  => 'rand'
    );//888分类随机文章

    $args_week = array(
        'category__in'  => 888,
        'date_query' => array(//一周内文章
            array(
                'year' => date( 'Y' ),
                'week' => date( 'W' ),
            ),
        ),
        'posts_per_page'  => 1,
        'paged'  => 1//只显示第一页
    );//888分类一周内文章

    $wp_query_week = new WP_Query( $args_week );//获取一周内文章

    if ( $wp_query->have_posts() ) {
        while ( $wp_query->have_posts() ) : $wp_query->the_post();
            get_template_part( 'content', get_post_format() );
            if ($wp_query->current_post == 1) {//第 2 篇文章后
                if ( $wp_query_week->have_posts() ) {
                    while ( $wp_query_week->have_posts() ) : $wp_query_week->the_post(); 
                        get_template_part( 'content', get_post_format() );
                    endwhile;
                    wp_reset_postdata();
                } else {
                    $wp_query_rand = new WP_Query($args_rand);
                    if ( $wp_query_rand->have_posts() ) {
                        while ( $wp_query_rand->have_posts() ) : $wp_query_rand->the_post(); 
                            get_template_part( 'content', get_post_format() );
                        endwhile;
                        wp_reset_postdata();
                    }
                }
            }
        endwhile;
    } else {
        get_template_part( 'content', 'none' );
    }
?>

注意:需要跟实际使用 WordPress 主题作相应修改。

WordPress 4.8.2 测试通过。


Originally Posted on Steemit & Blog by zhijun@zhijun.

WordPress 首页第 X 篇文章后插播随机文章 | Ecency