我有点困惑,为什么这不起作用-尽管必须说,我不太确定是什么apply_filters()
和add_filter
正在做,所以任何一般性的提示都会很好!
我想要一个查询,在一个帖子页面上显示之前的五篇帖子。我正在发送当前帖子的日期,并希望应用一个过滤器,过滤出早于此的帖子。
function sw_filter_posts_before( $where = \'\', $date) {
$where .= " AND post_date < \'" . $date . "\'";
return $where;
}
如何正确应用此选项?在实例化新的WP\\u查询对象之前,简单地使用add\\u filter或apply\\u filter似乎无法正常工作。
提前感谢!
编辑:为了更进一步,我想了解如何将变量传递到过滤器中,因为我无法从另一个函数传递$date。
下面是其他函数(这是wordpress中的ajax调用,因此我首先通过$\\u post变量获取当前页面的post ID):
function create_more_videos_sidebar() {
$id = $_POST[\'theID\'];
$args = array( \'post_type\' => \'videos\',
\'posts_per_page\' => 1,
\'p\' => $id
);
$wp_query = new WP_Query($args);
while ($wp_query->have_posts()) : $wp_query->the_post(); $do_not_duplicate = $post->ID;
$date = get_the_date(\'Y-m-d\');
endwhile;
$args = array( \'post_type\' => \'videos\',
\'posts_per_page\' => 5
);
add_filter( \'posts_where\', \'sw_filter_videos_before\' ); //don\'t know how to pass $date
$wp_query = new WP_Query($args);
remove_filter( \'posts_where\', \'sw_filter_videos_before\' );
//do loop stuff
$response = json_encode( array( \'result\' => $result ) );
header( "Content-Type: application/json" );
echo $response;
exit;
}
最合适的回答,由SO网友:Chip Bennett 整理而成
您试图筛选什么?我假设您正在尝试向名为posts_before
. 在这种情况下,您需要通过add_filter()
:
function mytheme_filter_posts_before( $where = \'\', $date) {
$where .= " AND post_date < \'" . $date . "\'";
return $where;
}
// Add function to the filter hook
add_filter( \'posts_before\', \'mytheme_filter_posts_before\' );
请注意,我更改了您的函数名。
filter_posts_before()
函数名过于泛化,很可能导致函数命名冲突。
编辑并澄清:
apply_filters()
是filter hook location, 由调用core code, 习惯于apply 任何added to the queue 按主题/插件(和核心)add_filter()
由调用Themes/Plugins (和核心),用于add filters to the queue 通过铁芯应用于吊钩编辑2根据您的上述评论,钩子是posts_where
. 因此,让我们尝试重新构建回调函数:
function mytheme_filter_posts_where( $where ) {
// Here, we need to figure out how to
// determine what date to use. In your
// code example, you call get_the_date(),
// but this function must be used inside
// the Loop. Let\'s try get_the_time()
// instead. You\'ll just need to come up
// with a way to determine what post ID to use.
$post = \'some_post_id\';
$date = get_the_time( \'Y-m-d\', $post );
$where .= " AND post_date < \'" . $date . "\'";
return $where;
}
// Add function to the filter hook
add_filter( \'posts_where\', \'mytheme_filter_posts_where\' );