0

为了使自定义帖子类型可过滤和可排序,我创建了一个自定义查询,该查询基于 url 中的变量工作,由 $_GET 访问。一种特定的情况打破了它。这是一个(未)指定的元键。在排序的情况下,在自定义字段上排序时需要元键。在其他情况下,可以忽略元密钥。但是,当我将变量设置为空时,查询不会产生任何帖子。如何处理空的 meta_key?

到目前为止,我尝试将变量设置为空 ($variable =''); 我将变量设置为空;我用过未设置。

if (isset($_GET["key"]) || isset($_GET["orderby"])){
if (isset($_GET["key"])) {$key = $_GET["key"];}
else {$key = '';}
if (isset($_GET["value"])) {$value = $_GET["value"]; echo $value;}
else {$value = '';}
if (isset($_GET["orderby"])) {$orderby = $_GET["orderby"];}
if ($orderby='meta_value'){$meta_key='averagerating';}
else {$orderby='';$meta_key='';}
if (isset($_GET["order"])) {$order = $_GET["order"];}
else {$order='';}
$cat = get_queried_object();
if (!empty($cat) && !is_post_type_archive('bedrijf')){
$category = $cat->name;
}

if (is_post_type_archive('bedrijf')){
$category = '';
$terms = get_terms( 'bedrijfs-category' ); 
    // convert array of term objects to array of term IDs
$category = wp_list_pluck( $terms, 'name' );    
}
global $post;
                $the_query ='';
                $args = array(
                    'post_type' => 'bedrijf',
                    'posts_per_page' => 10,
                    'meta_key' => ''.$meta_key.'',
                    'orderby'   => ''.$orderby.'',
                    'order' => ''.$order.'',
                    'tax_query' => array(
                                        array(
                                            'taxonomy' => 'bedrijfs-category',
                                            'field'    => 'name',
                                            'terms'    => $category
                                            )
                                        ),
                    'meta_query' => array(
                                        array(
                                            'key'=> ''.$key.'', 
                                            'value' => ''.$value.'',
                                            'compare' => 'LIKE'
                        )   
                    )
                );
 $the_query = new WP_Query($args); }

我想要的是在 meta_key => ''.$meta_key.'' 中插入空变量的解决方案,因此循环跳过了 meta_key 部分。

4

1 回答 1

0

从 $args 和(示例)中定义 meta_query 或 tax_query:

if($_GET['some_name'] !== ''){
  $meta_query = array(
    array(
         'taxonomy' => 'bedrijfs-category',
         'field'    => 'name',
         'terms'    => $category
    )
  );
  //define args with some_one para exists
  $args = array(
        'post_type' => 'bedrijf',
        'posts_per_page' => 10,
        'meta_key' => ''.$meta_key.'',
        'orderby'   => ''.$orderby.'',
        'order' => ''.$order.'',
        'meta_query' => $meta_query
  );

}else{

    //define args with some_one para not exists
    $args = array(
        'post_type' => 'bedrijf',
        'posts_per_page' => 10,
        'meta_key' => ''.$meta_key.'',
        'orderby'   => ''.$orderby.'',
        'order' => ''.$order.''
  );

 }

tax_query 是这样的

于 2019-09-08T09:09:35.850 回答