php - Wordpress - 按日期范围获取帖子

我试图从 WordPress 获取过去 7,30 和 365 天的帖子列表。

这是我使用的代码:

$args = array(
        'posts_per_page'=>10,
        'post_status'=>'publish',
        'post_type'=>'post'
    );
    if(isset($_GET['group'])){
        switch($_GET['group']){
            case 'week':
                $time = date('Y-m-d h:i:s',strtotime('-1 week'));
                break;
            case 'month':
                $time = date('Y-m-d h:i:s',strtotime('-1 month'));
                break;
            case 'year':
                $time = date('Y-m-d h:i:s', strtotime('-1 year'));
                break;
            default:
                $time = '';
                break;
        }
        if($time!=''){
            $args['pub_date'] = '>= "'.$time.'"';
        }
    }

    $query = new WP_Query( $args );

如果我错误记录 args 数组,我可以看到正在设置的时间戳。但是当我错误记录 WP_Query 对象时,我可以看到 SQL 查询:

SQL_CALC_FOUND_ROWS  wp_posts.* FROM wp_posts  INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id) WHERE 1=1  AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish') GROUP BY wp_posts.ID ORDER BY wp_postmeta.meta_value desc LIMIT 0, 10

此查询不包含我设置的 pub_date 日期范围。我怎样才能做到这一点?

最佳答案

在 this Thread 中归功于 MichaelH在 wp.org 论坛上。您可以修改它以满足您的要求。

<?php
  function filter_where($where = '') {
    //posts in the last 30 days
    //$where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
    //posts  30 to 60 days old
    //$where .= " AND post_date >= '" . date('Y-m-d', strtotime('-60 days')) . "'" . " AND post_date <= '" . date('Y-m-d', strtotime('-30 days')) . "'";
    //posts for March 1 to March 15, 2009
    $where .= " AND post_date >= '2009-03-01' AND post_date <= '2009-03-15'";
    return $where;
  }
add_filter('posts_where', 'filter_where');
query_posts($query_string);
?>

https://stackoverflow.com/questions/8034697/

相关文章:

php - 如何防止 mod_rewrite 处理 HTTP Post 请求?

r - 在 R 中缩放数据忽略特定列

php - 如何查看 cron 作业中返回的 php 错误

groovy - 在 Groovy 中使用 When and Then?

python - 如何将空查询集指定为非空查询集 : [ ] to []

bash - nohup 和 sed,重定向 stderr 和 stdout

c# - 在 C# 中将日期值转换为特定格式

perl - 我如何在运行时在 Perl 中绑定(bind) DBI 参数?

assembly - 如何用bios中断13h写入硬盘

php - 在 PHP 中使用不可打印字符作为分隔符?