簡體   English   中英

如何在自定義Wordpress循環中隱藏過去的帖子並顯示即將發布的X個帖子?

[英]How do I hide past posts in a custom Wordpress loop AND display X number of upcoming posts?

我正在嘗試在Wordpress中顯示日期等於或大於今天的帖子列表 - 目的是列出即將發生的事件。

這是我現在的代碼:

// Get the current date
    $current_date = date('M d, Y');
    $current_date = strtotime( $current_date );

    // Get the event date
    $post_date = get_the_time('M d, Y');
    $post_date = strtotime( $post_date );

    query_posts(array('category_name' => 'events',
                    'meta_query' => array(
                        array(
                         'key' => $post_date,
                         'value'=> $current_date,
                         'compare'=>'>='
                         )
                    ),
                    'showposts' => 4,
                    'orderby' => 'date', 
                    'order' => ASC));

    while (have_posts()) : the_post(); 

如你所見,我正在抓住當前日期和帖子的日期。 我知道這段代碼有效,因為我的代碼主要采用以下格式:

// Get the current date
$current_date = date('M d, Y');
$current_date = strtotime( $current_date );

query_posts(array('category_name' => 'events',
'showposts' => 4,
'orderby' => 'date', 
'order' => ASC));

while (have_posts()) : the_post(); 

// Get the date
$post_date = get_the_time('M d, Y');
$post_date = strtotime( $post_date );

// If older than current date, don't show it
if( $post_date >= $current_date ):

但問題是它找到帖子,然后將它們與當前日期進行比較。 因此,如果我想顯示我的10個帖子中的4個,但是因為它們已經過去而隱藏3個帖子,我實際上只在這里顯示1個帖子。

我需要與當前日期進行比較, 然后顯示該計算結果中的4個帖子。

任何幫助是極大的贊賞。 謝謝!

為此,您可以使用date_query作為query_posts()調用的一部分(代替meta_query )。

這將消除在查詢運行后檢查Posts日期的需要,因此您應該始終獲得您正在尋找的四個。

$today = getdate();
$args = array(
    'date_query'        => array(
        array(
            'year'      => $today["year"],
            'month'     => $today["mon"],
            'day'       => $today["mday"],
            'compare'   => '>=',
        ),
    ),
    'posts_per_page'    => 4,
    'orderby'           => 'date', 
    'order'             => ASC
);
query_posts($args);

注意:我強烈建議您查看WP_Query codex以獲取更多信息,因為其中有一些非常有用的參數。 這些可以幫助您進一步細化返回的Posts ,包括post_typepost_statuscat 當然,並非所有這些在所有情況下(或者可能在所有情況下)都與您相關,但它仍然值得一讀。

警告:請注意,一段時間之前, posts_per_page替換show_posts

更新

您在評論中提到上述代碼正在運行,但只檢索了一個Post 我最初的想法是,這是由兩件事之一引起的 -

  1. 你只有一個未來的Post ,因此沒有更多要顯示。
  2. 有些東西正在掛鈎您的查詢並更改LIMIT部分。

我建議查看一旦發出就傳遞給MySQL的查詢。 為此,請在query_posts($args)下方添加以下行並重新加載您的頁面。 -

global $wpdb;
echo '<pre>'; print_r($wpdb->last_query); echo '<pre>';

暫無
暫無

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

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