多值查询自定义字段WP

时间:2017-03-07 16:45:15

标签: wordpress advanced-custom-fields

我正试图在我的wordpress上实现查询。我想用两个过滤器显示post_type“enseignement”

  1. “循环”
  2. “代替”
  3. 此代码有效

    <?php if($_GET['cycle'] && !empty($_GET['cycle']))
    {
    $cycle = $_GET['cycle'];
    } else {
    }
    if($_GET['lieu'] && !empty($_GET['lieu']))
    {
    $lieu = $_GET['lieu'];
    } else {
    }
    ?>
    
    <?php
                    $args = array(
                    'post_type' => 'enseignement',
                    'posts_per_page' => 10,
                    'meta_query' => array(
                             'relation' => 'AND',
                            array(
                                'key' => 'cycle', // name of custom field
                                'value' => $cycle, // matches exactly "red"
                                'compare' => 'LIKE',
                                                            ),
                    array(
                         'key'     => 'lieu',
                         'value'   => $lieu,
                         'compare' => 'LIKE',
    
             ),
        ),
    
    
                    );
                $loop = new WP_Query( $args );
                while ( $loop->have_posts() ) : $loop->the_post(); ?>
                <?php get_template_part( 'content', 'enseignement', get_post_format() );?>
                <?php endwhile; ?>
    

    我的网址是这样的/?cycle = cycle1&amp; lieu = paris

    但如果我想要多个“周期”或多个“代替”这样/?cycle = cycle1,cycle2&amp; lieu = paris,马赛我不行。

    我如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

如果您的网址中包含以下内容:

/?cycle[]=cycle1&cycle[]=cycle2&lieu[]=paris&lieu[]=marseille

您将在$_GET['cycle']$_GET['lieu']参数中获得一个数组。 Visual of an array in a $_GET field

您可以将它们直接传递给WP_Query args,如下所示:

$args = array(
   'post_type'      => 'enseignement',
   'posts_per_page' => 10,
   'meta_query'     => array(
       'relation' => 'AND',
       array(
           'key'     => 'cycle', // name of custom field
           'value'   => $_GET['cycle'], // matches any field in the $_GET['cycle'] array
           'compare' => 'LIKE',
       ),
       array(
           'key'     => 'lieu',
           'value'   => $_GET['lieu'], // matches any field in the $_GET['lieu'] array
           'compare' => 'LIKE',
       ),
   ),
);