从 Wordpress 搜索中排除多个自定义分类术语

Exclude multiple custom taxonomies terms from Wordpress search

我正在从 Wordpress 搜索结果中排除任何帖子或自定义分类法设置为特定术语的自定义帖子。我希望能够简单地添加更多的分类法和术语(比如在数组中)而无需复制函数,并确保我能高效地完成它。

谁能推荐一个更简洁的函数来适应这个问题?

/* Exclude from WordPress Search using custom taxonomy */
add_action( 'pre_get_posts', function ( $query ) {
    if ( is_admin() || ! $query->is_main_query() ) {
        return;
    }

    // Exclude Terms by ID from Search and Archive Listings
    if ( is_search() || is_tax( 'marque' ) ) {    
        $tax_query = array([
            'taxonomy' => 'site_search',
            'field' => 'term_id',
            'terms' => [ exclude_page ],
            'operator' => 'NOT IN',
        ]);

        $query->set( 'tax_query', $tax_query );
    }
}, 11, 1 );


/* Exclude from WordPress Search using custom taxonomy */
add_action( 'pre_get_posts', function ( $query ) {
    if ( is_admin() || ! $query->is_main_query() ) {
        return;
    }

    // Exclude Terms by ID from Search and Archive Listings
    if ( is_search() || is_tax( 'marque' ) ) {    
        $tax_query = array([
            'taxonomy' => 'job_status',
            'field' => 'term_id',
            'terms' => [ closed ],
            'operator' => 'NOT IN',
        ]);

        $query->set( 'tax_query', $tax_query );
    }
}, 11, 1 );

您可以先尝试将数组中的所有数据定义为分类法/术语对(我已将数组嵌入到外部函数中,但可以直接将其添加到挂钩函数中) 。这样您就可以轻松地添加或删除数据。

然后我们使用 foreach 循环读取和设置税务查询中的数据。所以你的代码将是这样的:

// HERE set in the array your taxonomies / terms pairs
function get_custom_search_data(){
    return [
        'site_search' => [ 'exclude_page' ],
        'job_status'  => [ 'closed' ],
    ];
}

/* Exclude from WordPress Search using custom taxonomy */
add_action( 'pre_get_posts', 'multiple_taxonomy_search', 33, 1 );
function multiple_taxonomy_search( $query ) {
    if ( is_admin() || ! $query->is_main_query() ) {
        return;
    }

    // Exclude Terms by ID from Search and Archive Listings
    if ( is_search() || is_tax( 'marque' ) ) {
        // Set the "relation" argument if the array has more than 1 custom taxonomy
        if( sizeof( get_custom_search_data() ) > 1 ){
            $tax_query['relation'] = 'AND'; // or 'OR'
        }

        // Loop through taxonomies / terms pairs and add the data in the tax query
        foreach( get_custom_search_data() as $taxonomy => $terms ){
            $tax_query[] = [
                'taxonomy' => $taxonomy,
                'field' => 'slug', // <== Terms slug seems to be used
                'terms' => $terms,
                'operator' => 'NOT IN',
            ];
        }

        // Set the defined tax query
        $query->set( 'tax_query', $tax_query );
    }
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。未经测试,应该可以。