我正在开发一个小部件。我想显示过去 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' );
现在这是我的小部件类:
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') );
但它也不起作用。