从搜索中排除自定义 post 类型的 children

Exclude children of custom post type from search

我有一个自定义 post 类型的 'location'。然后,我有 children 个页面用于该 cpt 的每个页面。所以它看起来像这样,"www.example.com/location/location-name/child-page/",每个 child 页面都使用 "location-product-services.php" 的 post 模板。所以我想做的是从搜索结果中排除这个 cpt 的 children。

我正在尝试通过检查元数据来查看它是否在使用该模板。我似乎无法让它工作。任何帮助都会很棒。

这是我目前拥有的-

// Exclude local product and services pages from search result.
function location_subpages_exclude_search( $query ) {
    if ( is_search() && !is_admin()) {
        $query->set('meta_query',
            array(
                'key' => '_wp_page_template',
                'value' => 'location-product-services.php',
                'compare' => '!='
            )
        );
    }
}

add_action('pre_get_posts', 'location_subpages_exclude_search');

提前致谢。

首先,每当我想修改搜索时,我几乎只使用 Relevanssi 插件。但是要以编程方式搜索,我认为这就是您所追求的:

$taxonomy = 'location';
$terms = get_terms($taxonomy, array( 'parent' => 0, 'search' => $query ) );

if ( $terms && !is_wp_error( $terms ) ) :
?>
    <ul>
        <?php foreach ( $terms as $term ) { ?>
            <li><a href="<?php echo get_term_link($term->slug, $taxonomy); ?>"><?php echo $term->name; ?></a></li>
        <?php } ?>
    </ul>
<?php endif;?>

使用函数 get_terms 搜索您的 CPT,'search' 是您的 $query(您可以考虑使用 SQL 通配符 '%' 包装搜索字符串)和 'parent'=>0 returns 仅顶层。

我明白了。 首先,我得到了我的 post 类型的所有父页面,使用 get_pages() 将它们全部抓取。

遍历每个父页面并 运行 另一个 get_pages() 用于该父页面的子页面。

function SearchFilter($query) {

    if ($query->is_search) {

        $args = array(
            'hierarchical' => 0,
            'post_type' => 'location',
            'parent' => 0, //returns all top level pages 
            'post_per_page' => -1
        ); 

        $parents = get_pages($args);
        $excludes = array();

        foreach($parents as $parent) : 
            $args = array(
                'post_type' => 'location',
                'child_of' => $parent->ID,
                'post_per_page' => -1
            ); 
            $children = get_pages($args); 
            foreach($children as $child): 
                array_push($excludes, $child->ID);
            endforeach;
        endforeach;

        $query->set('post__not_in', $excludes);
    }
    return $query;
 }
 add_filter('pre_get_posts','SearchFilter');