自定义查询,用于显示从当前日期起超过 8 个月的 WordPress 自定义帖子类型


Custom query for displaying WordPress custom post types that are more than 8 months old from current date

我在 for 循环中在 Wordpress 中使用以下自定义查询,使我能够为我为"新闻"创建的自定义帖子类型的前 8 个月创建选项卡式存档。

这非常有效,但是我希望然后在"旧新闻"标题下显示每个较旧的帖子。我正在努力弄清楚如何在任何时候将超过8个月的帖子与当前日期分开。

谁能建议我一个自定义查询结构,使我能够做到这一点。

这是我用来在其相关容器中输出 CPT 的代码。

<?php for($i = $this_month-1; $i > $this_month-8; $i--) :
        if($i==-1){$m=11;}
        if($i==-2){$m=10;}
        if($i==-3){$m=9;}
        if($i==-4){$m=8;}
        if($i==-5){$m=7;}
        if($i==-6){$m=6;}
        if($i==-7){$m=5;}
        if($i==-8){$m=4;}
        else{$m=$i;}
        query_posts( array(
            'post_type' => 'news',
            'posts_per_page' => '-1',
            'orderby' => 'date',
            'order' => 'ASC',
            'monthnum'=>$m
        ) );  
.......
你可以

试试这个

<?php 
    add_filter('posts_where', 'filter_where');
    query_posts( array('post_type' => 'news', 'posts_per_page' => '-1', 'orderby' => 'date')); 
    function filter_where($where = ''){
        $where .= " AND post_date < '".date('Y-m-d', strtotime('-8 month'))."'";
        return $where;
    }
    remove_filter('posts_where', 'filter_where');
    if (have_posts()) : 
        while (have_posts()) : the_post();
        // your code
        endwhile;
    endif;
    wp_reset_query();
?>

更新:也许这可以帮助您。

$args = array(
    'post_type' => 'news',
    'posts_per_page' => '-1',
    'orderby' => 'date',
    'year'     => date('Y'), // for current year, date('Y')-1 for 1 year ago
    'monthnum' => $m, // the month in the loop
    'order'    => 'ASC'
);
query_posts( $args );

我对wordpress不太了解,但可以在逻辑上帮助你。据我所知,这可以通过检查查询中的"WHERE creation_date <8 个月"等条件来完成,同时检索"旧新闻"类别的帖子。所以首先获取当前日期。

<?php $today = date('Y-m-d'); ?>

然后从中减去 8 个月,你会得到一个 8 个月大的日期

<?php $eight_month = date('Y-m-d',strtotime("-8 month $today")); ?> 

现在,您可以在查询中使用 $eight_month,因此查询将如下所示。检查您存储在数据库中以进行发布发布的日期格式,如果它与格式"Y-m-d"不同,请相应地更改我的

"从creation_date <'$eight_MONTH'的帖子中选择 *"

希望这是你想要的,并在你的项目中帮助你。祝你好运,祝你有美好的一天