簡體   English   中英

用於顯示從當前日期起超過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,這樣您的查詢就會是這樣的。 檢查您存儲在數據庫中的日期格式以便發布,如果與格式“Ymd”不同,則相應地更改我的格式

“SELECT * FROM posts WHERE creation_date <'$ eight_month'”

希望這是你想要的,並幫助你的項目。 祝你好運,祝你有個美好的一天

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM