使用Advansed自定义字段过滤,Wordpress

时间:2018-03-24 07:16:04

标签: wordpress filter filtering advanced-custom-fields

我在我的网站上有过滤器: My filter form

过滤算法是: Filtering algorithm

此算法的PHP代码:

$GLOBALS['my_query_filters'] = array( 
    'field_1'   => 'work',
    'field_2'   => 'visa'
);

add_action('pre_get_posts', 'my_pre_get_posts', 10, 1);

function my_pre_get_posts( $query ) {
    if(is_admin()) return;

    if(!$query->is_main_query()) return;

    $meta_query = $query->get('meta_query');
    $tax_query  = $query->get('tax_query');
    $k = 0;

    foreach($GLOBALS['my_query_filters'] as $key => $name) {
        if(empty($_GET[$name])) continue;

        $value = explode(',', $_GET[$name]);

        foreach($value as $item) {
            $meta_query[$k] = array(
                'key'     => $name,
                'value'   => $item,
                'type'    => 'CHAR',
                'compare' => 'LIKE'
            );

            $k++;
        }
    } 

    if($_GET['cat']) {
        $tax_query[] = array(
            array(
                'taxonomy' => 'category',
                'field'    => 'id',
                'terms'    => $_GET['cat'],
                'operator' => 'IN'
            )
        );
        $query->set('tax_query', $tax_query);
    }

    $query->set('meta_query', $meta_query);
}

但我需要更改过滤算法: New filtering algorithm

我不太了解WP_Query()。你能帮我编辑$ meta_query吗?

1 个答案:

答案 0 :(得分:0)

我将过滤器更改为:

function my_pre_get_posts( $query ) {
    if(is_admin()) return;

    if(!$query->is_main_query()) return;

    $meta_query = $query->get('meta_query');
    $tax_query  = $query->get('tax_query');

    foreach($GLOBALS['my_query_filters'] as $key => $name) {
        if(empty($_GET[$name])) continue;

        $meta_query['relation'] = 'AND';
        $meta_query_inner['relation'] = 'OR';

        $value = explode(',', $_GET[$name]);
        $k = 0;
        foreach($value as $item) {
            $meta_query_inner[$k] = array(
                'key'     => $name,
                'value'   => $item,
                'type'    => 'CHAR',
                'compare' => 'LIKE'
            );

            $k++;
        }
        $meta_query[] = $meta_query_inner;
    } 

    if($_GET['cat']) {
        $tax_query[] = array(
            array(
                'taxonomy' => 'category',
                'field'    => 'id',
                'terms'    => $_GET['cat'],
                'operator' => 'IN'
            )
        );
        $query->set('tax_query', $tax_query);
    }

    $query->set('meta_query', $meta_query);
}

似乎有效:)