我正在尝试在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个帖子。
非常感谢任何帮助。谢谢!
答案 0 :(得分:2)
为此,您可以使用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>';