【问题标题】:Adding an array from a query string to a WP meta_query将查询字符串中的数组添加到 WP meta_query
【发布时间】:2016-06-03 21:36:24
【问题描述】:

我正在从查询字符串中收集值作为数组。然后收集这些值并将它们放入“meta_query”的值中。

我在 WP_Query 没有输出任何内容时遇到问题。我觉得'meta_query'中的第二个数组有问题。

我尝试将比较更改为“LIKE”,这会显示所有内容而不是查询中的内容。

查询字符串:

?variable[]=value1&variable[]=value2

PHP 代码:

<?php
$variable_selected = $_GET['variable'];

$filter = array(
    'post_type' => 'my_custom_post_type',
    'meta_query' => array(
        'relation' => 'OR',
         array(
            'key' => 'my_post_field',
            'value' => $variable_selected,
            'compare' => 'IN'
            )
        )

    );

    $posts = new WP_Query( $filter  );

对此的任何帮助都会很棒。

【问题讨论】:

    标签: php arrays wordpress query-string


    【解决方案1】:

    我将首先在 $variable_selected 上运行 var_dump 以确保您获得了所需的数组。此外,由于您只使用一个元键/值字段,您的查询中可能不需要 OR,因此您可以执行以下操作。希望有帮助。

    <?php
    $variable_selected = $_GET['variable'];
    
    // Use the var_dump to test to see if array is being pulled in properly.
    var_dump ( $variable_selected );    
    
    $filter = array(
    'post_type' => 'my_custom_post_type',
    'meta_query' => array(
         array(
            'key' => 'my_post_field',
            'value' => $variable_selected,
            'compare' => 'IN'
            )
        )
    
    );
    
    $posts = new WP_Query( $filter  );
    

    【讨论】:

    • 感谢您的回复,但是在检查了变量并得到了我想要的数组之后,我仍然没有得到任何结果。我一起消除了变量并将我的数组放入 meta_query 中,我得到了相同的结果,什么都没有。
    【解决方案2】:

    这使得 meta_query 动态取决于查询字符串中有多少值。

    $meta_query = array();
    if ( ! empty( $_GET["variable"] ) ) {
        if ( is_array( $_GET["variable"] ) ) {
            $meta_query['relation'] = 'OR';
            foreach ( $_GET["variable"] as $value ) {
                $meta_query[] = array(
                    'key' => 'my_post_field',
                    'value' => sanitize_text_field( (string) $value ),
                    'compare' => 'LIKE'
                );
            }
        } else {
           $meta_query = array(
                'key' => 'my_post_field',
                'value' => sanitize_text_field( (string) $_GET["variable"] ),
                'compare' => '='
           );
        }
     }
     $filter = array(
        'post_type' => 'my_custom_post_type',
        'meta_query' => array(
           'relation' => 'OR',
           $meta_query
     )
     );
     $posts = new WP_Query( $filter );
    

    【讨论】:

      猜你喜欢
      • 2022-10-25
      • 2011-02-11
      • 1970-01-01
      • 2012-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多