![](/img/trans.png)
[英]How do I query posts custom relationship field and include parsed search term into loop and display results in WordPress
[英]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_type
, post_status
和cat
。 當然,並非所有這些在所有情況下(或者可能在所有情況下)都與您相關,但它仍然值得一讀。
警告:請注意,一段時間之前, posts_per_page
替換 。 show_posts
您在評論中提到上述代碼正在運行,但只檢索了一個Post
。 我最初的想法是,這是由兩件事之一引起的 -
Post
,因此沒有更多要顯示。 LIMIT
部分。 我建議查看一旦發出就傳遞給MySQL
的查詢。 為此,請在query_posts($args)
下方添加以下行並重新加載您的頁面。 -
global $wpdb;
echo '<pre>'; print_r($wpdb->last_query); echo '<pre>';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.