Исключите несколько пользовательских терминов таксономии из поиска Wordpress


Я исключаю из результатов поиска 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 );
Author: LoicTheAztec, 2018-09-02

1 answers

Вы можете сначала попробовать определить все ваши данные в массиве сначала как пары таксономий/терминов (я встроил массив во внешнюю функцию, но его можно добавить непосредственно в подключенную функцию). Таким образом, вы можете легко добавлять или удалять данные.

Затем мы используем цикл 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 файл вашей активной дочерней темы (или активной темы). Непроверенный, он должен работа.

 2
Author: LoicTheAztec, 2018-09-02 20:50:53