题
如何通过两个自定义元字段,一个开始日期和一个结束日期限制查询?这就是我的数据的样子:
meta_key | meta_value | ------------------------| start_date | 20100131 | //Jan 15, 2010 end_date | 20100206 | //Feb 6, 2010 ------------------------' $today = date(YYYYMMDD);
该帖子将显示是否 start_date = $today
它将到期 end_date = $today
.
更新
这是我的single.php上的结构
第一个查询我在这里使用您的答案
<?php
query_posts( $query_string );
if (have_posts()) : while (have_posts()) : the_post();
?><a href="<?php the_permalink() ?>"><?php the_title() ?></a><br /><?php
endwhile; endif;
wp_reset_query();
?>
以及使用常规WordPress函数的第二个查询,但是第二个查询无法正常工作
<?php
query_posts('showposts=5&meta_key=start_date&meta_compare=>&meta_value='.date("Ymd"));
if (have_posts()) : while (have_posts()) : the_post();
?><a href="<?php the_permalink() ?>"><?php the_title() ?></a><br /><?php
endwhile; endif;
wp_reset_query();
?>
解决方案
再次编辑以演示添加和删除过滤器:
将这些一般功能包括在您的 functions.php. 。这些是您将通过以下两个元值限制查询的循环的过滤器:
function date_check_join( $join ) {
global $wpdb;
$join .= " JOIN ".$wpdb->postmeta." AS startdate ON
(".$wpdb->posts.".ID = startdate.post_id AND
startdate.meta_key = 'start_date')
JOIN ".$wpdb->postmeta." AS enddate ON
(".$wpdb->posts.".ID = enddate.post_id AND
enddate.meta_key = 'end_date')";
return $join;
}
function date_check_where( $where ) {
$today = date('Ymd');
$where .= " AND startdate.meta_value <= $today
AND enddate.meta_value >= $today";
return $where;
}
现在,在要包含这些过滤器的页面上,将它们添加到循环之前要过滤并之后将其删除。例如:
add_filter( 'posts_join', 'date_check_join' );
add_filter( 'posts_where', 'date_check_where' );
query_posts( "yourqueryhere" );
if (have_posts()) : while (have_posts()) : the_post();
// This loop will only includes where today is between start_date and end_date
endwhile; endif;
query_posts( "anotherqueryhere" );
if (have_posts()) : while (have_posts()) : the_post();
// This loop also only includes where today is between start_date and end_date
endwhile; endif;
remove_filter( 'posts_join', 'date_check_join' );
remove_filter( 'posts_where', 'date_check_where' );
query_posts( "thirdqueryhere" );
if (have_posts()) : while (have_posts()) : the_post();
// This loop is not affected by the filters, so you can query for posts
// where start_date is in the future, or end_date in the past, etc.
endwhile; endif;
您只需要在搜索前将条件添加到“ posts_join”和“ posts_where”过滤器中,然后将其删除(否则这些条件将应用于网站上的所有内容,包括页面,菜单等)
如果您只能通过比较一个字段来简化这一点,则可以使用 meta_compare
属性 内置在WP_QUERY对象中。您可以为start_date安排帖子(因此它们不会提前显示),然后在查询时将日期与end_date自定义字段进行比较。
其他提示
这个问题的答案: 如何通过视图更改循环到订购帖子(使用wp-postviews插件) 向您展示如何通过自定义字段进行排序。
查看cooly_posts()的Codex文档: http://codex.wordpress.org/template_tags/query_posts, ,查看自定义字段部分。
然后,您需要做的就是在循环中包含一个测试以跳过($ nvoy <start_date或$ tovers> end_date)