You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为发布100天内的articles类型文章添加标签实现筛选需求

问题描述

我有一个名为articles的文章类型,希望为发布时间在当前日期前100天内的文章添加标签,以此筛选并展示这类最新文章,让用户可通过该标签筛选查看「近期新增文章」(即发布于当前日期前100天内的文章)。以下是我编写的代码:

if ( $query->have_posts() ) {
    ?>
    Found <?php echo $query->found_posts; ?> Results<br />
    <div class='search-filter-results-list'>

        <?php
        while ( $query->have_posts() ) {
            $query->the_post();

            // Get post published date
            $post_date = get_the_date('Ymd');
            $current_date = current_time('Ymd');
            $future_date = date('Ymd', strtotime('-100 days'));

            // Check if post published date is -100 days before the current date
            $class_to_add = ($post_date <= $current_date && $post_date >= $future_date) ? ' your-custom-class' : '';
            ?>

            <div class='search-filter-result-item<?php echo esc_attr($class_to_add); ?>'>
                <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
                <p><br /><?php the_excerpt(); ?></p>

                <?php if ( has_post_thumbnail() ) : ?>
                    <p><?php the_post_thumbnail( 'small' ); ?></p>
                <?php endif; ?>

                <p><?php the_category(); ?></p>
                <p><?php the_tags(); ?></p>
                <p><small><?php the_date(); ?></small></p>
                <hr />
            </div>

            <?php
        }
        ?>
    </div>
    <?php
}

请问各位有什么改进建议吗?谢谢!


改进建议

1. 提前在查询阶段过滤文章,提升性能

当前代码是先拉取所有文章,再在循环内逐个判断日期,这会浪费资源加载不需要的内容。直接修改WP_Query参数,只查询100天内的articles类型文章,能大幅减少数据库查询和循环处理的压力:

$args = array(
    'post_type' => 'articles',
    'date_query' => array(
        array(
            'after' => '-100 days',
            'inclusive' => true,
        ),
    ),
    'posts_per_page' => 10, // 按需调整每页显示数量,-1代表全部
);
$query = new WP_Query($args);

2. 实现真正的标签添加(而非仅CSS类)

你当前的代码只给元素加了CSS类,无法支持用户通过WordPress标签筛选。可以通过两种方式实现自动添加「近期新增文章」标签:

方式一:循环内动态判断并添加(适合实时更新)

// 在$query->the_post()之后添加
$post_id = get_the_ID();
$recent_tag_name = '近期新增文章';

// 检查标签是否存在,不存在则创建
$tag = get_term_by('name', $recent_tag_name, 'post_tag');
if (!$tag) {
    $tag_result = wp_insert_term($recent_tag_name, 'post_tag');
    if (is_wp_error($tag_result)) return;
    $tag_id = $tag_result['term_id'];
} else {
    $tag_id = $tag->term_id;
}

// 用时间戳判断是否符合条件
$post_timestamp = get_post_time('U');
$cutoff_timestamp = strtotime('-100 days');
if ($post_timestamp >= $cutoff_timestamp) {
    wp_set_post_terms($post_id, array($tag_id), 'post_tag', true); // true表示追加标签,不覆盖原有标签
}

注意:如果文章数量大,循环内频繁调用wp_set_post_terms会影响性能,建议结合定时任务批量处理。

方式二:发布时自动添加+定时清理(更高效)

用save_post钩子给新发布的articles自动加标签,再用WP Cron定期移除超过100天的文章的该标签:

// 发布文章时自动添加标签
add_action('save_post_articles', 'add_recent_tag_on_publish', 10, 3);
function add_recent_tag_on_publish($post_id, $post, $update) {
    if (wp_is_post_autosave($post_id) || wp_is_post_revision($post_id)) return;
    if ($post->post_status !== 'publish') return;

    $recent_tag_name = '近期新增文章';
    $tag = get_term_by('name', $recent_tag_name, 'post_tag');
    if (!$tag) {
        $tag_result = wp_insert_term($recent_tag_name, 'post_tag');
        if (is_wp_error($tag_result)) return;
        $tag_id = $tag_result['term_id'];
    } else {
        $tag_id = $tag->term_id;
    }
    wp_set_post_terms($post_id, array($tag_id), 'post_tag', true);
}

// 定时清理过期标签(每天执行一次)
add_action('daily_clean_recent_tags', 'remove_expired_recent_tags');
if (!wp_next_scheduled('daily_clean_recent_tags')) {
    wp_schedule_event(time(), 'daily', 'daily_clean_recent_tags');
}
function remove_expired_recent_tags() {
    $recent_tag = get_term_by('name', '近期新增文章', 'post_tag');
    if (!$recent_tag) return;

    $args = array(
        'post_type' => 'articles',
        'posts_per_page' => -1,
        'date_query' => array(
            array(
                'before' => '-100 days',
                'inclusive' => false,
            ),
        ),
        'tax_query' => array(
            array(
                'taxonomy' => 'post_tag',
                'field' => 'term_id',
                'terms' => $recent_tag->term_id,
            ),
        ),
    );
    $expired_posts = new WP_Query($args);
    if ($expired_posts->have_posts()) {
        while ($expired_posts->have_posts()) {
            $expired_posts->the_post();
            wp_remove_object_terms(get_the_ID(), $recent_tag->term_id, 'post_tag');
        }
        wp_reset_postdata();
    }
}

3. 用时间戳做日期判断更可靠

当前用Ymd字符串比较虽然可行,但用Unix时间戳能避免格式问题,逻辑更直观:

// 移到循环外部,避免重复计算
$cutoff_timestamp = strtotime('-100 days');

while ( $query->have_posts() ) {
    $query->the_post();
    $post_timestamp = get_post_time('U');
    $class_to_add = ($post_timestamp >= $cutoff_timestamp) ? ' your-custom-class' : '';
    // 后续渲染代码不变
}

4. 代码结构优化

  • 把重复计算的日期逻辑移到循环外,减少不必要的运算
  • 循环结束后调用wp_reset_postdata(),重置全局post对象,避免影响后续查询:
while ( $query->have_posts() ) {
    // 循环内容
}
wp_reset_postdata(); // 新增这一行

5. 添加标签筛选入口

给用户提供筛选链接,点击后直接查看带有「近期新增文章」标签的文章:

$recent_tag = get_term_by('name', '近期新增文章', 'post_tag');
if ($recent_tag) {
    echo '<p><a href="' . esc_url(get_tag_link($recent_tag->term_id)) . '">查看近期新增文章</a></p>';
}

内容的提问来源于stack exchange,提问作者Brad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 08:32:27