我正在开发一个Widget。我想显示过去30天内的所有帖子。我将使用此代码段(来自CODEX):
// Create a new filtering function that will add our where clause to the query
function filter_where( $where = '' ) {
// posts in the last 30 days
$where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
return $where;
}
add_filter( 'posts_where', 'filter_where' );
$query = new WP_Query( $query_string );
remove_filter( 'posts_where', 'filter_where' );
现在这是我的widget类:
class Okunma_Sayisina_Gore_Listele extends WP_Widget {
public function __construct() {
parent::__construct(
'okunma_sayisina_gore_listele', // Base ID
'Okunma_Sayisina_Gore_Listele', // Name
array( 'description' => 'Son n gün içinde yazılmış yazıları okunma sayılarına göre sıralayarak listeler', ) // Args
);
}
public function filter_where( $where = '' ) {
// posts in the last 30 days
$where .= " AND post_date > '" . date('Y-m-d', strtotime('-30 days')) . "'";
return $where;
}
public function widget( $args, $instance ) {
global $wpdb;
extract( $args );
$title = apply_filters( 'widget_title', $instance['title'] );
$n = intval($instance['n']);
echo $before_widget;
if ( ! empty( $title ) )
echo $before_title . $title . $after_title;
/* IT'S NOT WORKING */
add_filter( 'posts_where', array('this','filter_where') );
$posts = get_posts(array(
"number_posts" => $n,
"post_type" => "post",
));
remove_filter( 'posts_where', array('this','filter_where') );
foreach ($posts as $post)
{
echo $post->post_title;
}
echo $after_widget;
}
public function update( $new_instance, $old_instance ) {
...
}
public function form( $instance ) {
...
}
}
add_action( 'widgets_init', create_function( '', 'register_widget( "Okunma_Sayisina_Gore_Listele" );' ) );
过滤器无效。这个小工具列出了所有帖子,不仅是过去30天。
另外,我试过
add_filter( 'posts_where', array('Okunma_Sayisina_Gore_Listele','filter_where') );
而不是
add_filter( 'posts_where', array('this','filter_where') );
但它也不起作用。
答案 0 :(得分:0)
好的,我在Filter Reference找到了答案。我忘了'suppress_filters' => FALSE
。
$posts = get_posts(array(
"number_posts" => 4,
"post_type" => "post",
'suppress_filters' => FALSE
));