WordPress代码实现历史上的今天功能

WordPress代码实现历史上的今天功能

本功能是展示站内历史上的今天发布的文章,而不是之前历史上发生的大事。所以想正常使用本功能,首先需要的是你站点运行超过1年了,如果还不到一年,那自然不会有什么历史上的今天了。

前面本站分享了wordpress历史上的今天插件:WP-Today,使用插件的方式来实现历史上的今天这个功能,今天我就给大家带来如何无需插件使用代码来实现历史上的今天这个功能,本功能是使用自带的date_query来实现。

实现方法

下面的代码加入到functions.php

function fa__in_histroy(){
    $ = getdate();
    $args = (
        'date_query' => (
            array(
                'year'      => $today['year'],
                'compare'   => '!=',
            ),
            array(
                'month' => $today['mon'],
                'day'   => $today['mday'],
            ),
        ),
    );
    $postlist = get_posts($args);
    $html = '<h3 class="tih-title">历史上的今天</h3><ul class="tih-title-list">';
    if(!empty($postlist)){
        foreach ($postlist as $key => $post) {
            $html .= '<li class="tih-title-item"><a href="' . get_permalink($post->ID) . '" title="' . $post->post_title . '">' . $post->post_title . '</a></li>';
        }
        $html .= '</ul>';
        return $html;
    }
}

注意,在这个循环中是不能直接调用各种wp文章函数的,如需使用wp文章函数,则需要使用setup_postdata()wp_reset_postdata()

调用方法

如果是添加到文章末尾,可直接使用如下钩子,直接添加到functions.php中即可

function add_today_in_histroy($content){
    global $post;
    return $content . today_in_histroy();
}
add_filter('the_content','add_today_in_histroy');

如果是自定义位置,则使用

<?php echo today_in_histroy(); ?>

本文就不提供CSS样式了,如需html样式,可根据html结构进行定制,我已经添加了相应class