【问题标题】:Limit wp_count_posts to the last 7 days将 wp_count_posts 限制为过去 7 天
【发布时间】:2021-01-05 18:31:05
【问题描述】:

我想显示帖子类型中的帖子总数,但将其限制为最近 7 天。

这是我当前的代码,成功显示了自定义帖子类型中的帖子总数。

<?php $published_posts = wp_count_posts($type = 'games')->publish; echo $published_posts;?>

有没有办法通过传递额外的参数?怎么办?

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    不幸的是,wp_count_posts() 不会让您到达那里,它只会为您提供所有 post_type 的固定数字(以及它是否可读)。

    WP_Query 类一开始似乎有点吓人,但它应该可以满足您的需求,因为它内置了更精细的控制,即Date Parameters

    初始化WP_Query 后,您可以使用found_posts 属性(不是post_count!)查看它返回了多少帖子。类似于以下内容:

    $week_query_args = array(
        'posts_per_page' => -1,    // No limit
        'fields'         => 'ids', // Reduce memory footprint
        'post_type'      => 'your_post_type',
        'date_query'     => array(
            array( 'after' => '1 week ago' )
        )
    );
    
    $week_query = new WP_Query( $week_query_args );
    
    echo "We have {$week_query->found_posts} for the past 7 days";
    

    【讨论】:

    • 非常感谢,我认为 WP_Query 对此有点矫枉过正,但似乎使用的资源可能更少(尤其是考虑到它只检查 ID)?我来到了这个同样有效的解决方案。谢谢! <?php $querystr = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'games' AND post_date >= DATE_SUB(CURRENT_DATE, INTERVAL 7 DAY) LIMIT 0, 30"); if (0 < $querystr) $querystr = number_format($querystr); echo $querystr.' last 7 days';?>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-07
    • 2022-07-20
    • 2013-01-25
    • 2020-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多