0

私はウィジェットを開発しています。過去 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') );

しかし、それも機能していません。

4

1 に答える 1

0

OK、 Filter Referenceで答えが見つかりました。忘れ'suppress_filters' => FALSEました。

$posts = get_posts(array(
    "number_posts" => 4,
    "post_type"    => "post",
    'suppress_filters' => FALSE
));
于 2012-07-23T16:48:54.773 に答える