3

我从 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 );
4

1 回答 1

2

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

然后我们使用一个 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 文件中。未经测试,它应该工作。

于 2018-09-02T18:51:08.167 回答