过滤器应用于意外查询

时间:2019-05-06 21:00:14

标签: wordpress

我正在将get_the_excerptget_the_content过滤器应用于自定义帖子类型的搜索结果。过滤器似乎正在应用于小部件中的其他查询,而不仅仅是搜索查询。有没有一种方法可以将过滤器限制为仅适用于搜索查询。

我试图限制过滤器,使其仅在特定条件下适用,但似乎不符合条件:

添加过滤器

add_filter( 'get_the_excerpt', 'CourseStorm_Templates::coursestorm_alter_search_results_content' );
add_filter( 'get_the_content', 'CourseStorm_Templates::coursestorm_alter_search_results_content' );

过滤器代码

// Get post taxonomies
$taxonomies = get_post_taxonomies();

// Alter post output for courses on the search page.
if ( in_array( 'my_custom_post_type', $taxonomies ) && is_search() && is_main_query()) :
    // do stuff to alter display of CPT
endif;

我在一个小部件中有一个查询,当该小部件显示在搜索页面上时,此更改将被应用。我已经确认小部件查询至少会失败一个条件(is_search()),因此不应应用它。

小部件查询

$query_args = array(
    'post_type'   => 'my_custom_post_type',
    'tax_query'   => array(
        array(
            'taxonomy' => 'my_category',
            'field' => 'id',
            'terms' => '0',
        )
    ),
);
$the_query = new WP_Query( $query_args );

if ( $the_query->have_posts() ) :
    while ( $the_query->have_posts() ) : $the_query->the_post();
        $post_id = $the_query->post->ID;
        $meta = get_post_meta( $post_id );
        $title = get_the_title( $post_id );
        the_excerpt(); // the alterations from the filter are getting applied here.
    endwhile;

    wp_reset_query();
endif;

我希望过滤器仅应用于搜索结果,而不应用于搜索页面上显示的窗口小部件内容。

1 个答案:

答案 0 :(得分:0)

您可以使用remove_filter check docs来删除小部件WP_Query的过滤器。根据小部件侧边栏在主帖子循环之前或之后的位置,可以在自定义WP_Query之后添加过滤器。因此您的Widget查询将如下所示:

// remove filters before
remove_filter( 'get_the_excerpt', 'CourseStorm_Templates::coursestorm_alter_search_results_content' );
remove_filter( 'get_the_content', 'CourseStorm_Templates::coursestorm_alter_search_results_content' );

$the_query = new WP_Query( $query_args );

if ( $the_query->have_posts() ) :
    while ( $the_query->have_posts() ) : $the_query->the_post();
        $post_id = $the_query->post->ID;
        $meta = get_post_meta( $post_id );
        $title = get_the_title( $post_id );
        the_excerpt();
    endwhile;

    wp_reset_query();
endif;

// add filters back
add_filter( 'get_the_excerpt', 'CourseStorm_Templates::coursestorm_alter_search_results_content' );
add_filter( 'get_the_content', 'CourseStorm_Templates::coursestorm_alter_search_results_content' );