如何从搜索结果中排除特定页面(和子页面)?

时间:2020-06-23 作者:Matthew Brown aka Lord Matt

如何从搜索结果中排除特定页面(和子页面)?

我看过一些帖子,展示了如何排除所有页面。我不想那样。我想把一个页面和它的子页面作为目标,排除它们,并且只排除它们。

1 个回复
SO网友:ViralP

// Filter to exclude a page and it\'s child pages from search query
function myfilter_exclude_pages_from_search( $query ) {

    // Save the post id of the page to be excluded in $parent_post_id_to_exclude
    $parent_post_id_to_exclude = 111; // Replace 111 with actual page id
    // Convert the post id to an array
    $parent_post_id_arr = array( $parent_post_id_to_exclude ); 

    // Apply filter only if this is a search query and not on admin panel
    if ( $query->is_search && !is_admin() ) {

        // Search only for pages
        $query->set( \'post_type\', \'page\');

        // Exclude the page id
        $query->set( \'post__not_in\', $parent_post_id_arr );

        // Exclude all child pages of selected page id
        $query->set( \'post_parent__not_in\', $parent_post_id_arr );
    }
    return $query;
}
add_filter( \'pre_get_posts\', \'myfilter_exclude_pages_from_search\' );
请阅读下面的文章了解pre_get_posts
https://www.wpbeginner.com/plugins/how-to-exclude-specific-pages-authors-and-more-from-wordpress-search/

WP\\U查询参数参考:https://developer.wordpress.org/reference/classes/wp_query/

相关推荐

Woocommerce budget search

我有woo commerce设置。现在的要求就像说,如果我搜索预算,比如说5000,它应该显示总价格为5000的产品(例如一个价格为3000的产品和一个2000奖的产品)。我们该怎么做,请帮忙。