Edited again to demonstrate adding and removing filters:
将这些常规功能包括在
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\\u join”和“posts\\u where”过滤器中,然后将其删除(否则这些条件将应用于您网站上的所有内容,包括页面、菜单等)
如果可以通过仅比较一个字段来简化此操作,那么可以使用meta_compare
attribute 内置于WP\\U查询对象中。您可以为帖子安排开始日期(这样它们就不会提前显示),然后在查询时将日期与结束日期自定义字段进行比较。