WP查询 - 如果存在则按meta_key排序,否则为title

时间:2017-10-09 19:41:49

标签: wordpress meta-key

如果存在此类密钥,我首先尝试获取按数字meta_key排序的自定义帖子列表,如果没有密钥,则按标题继续排序。

我的意思是:

  1. AObject(object_order => 1)
  2. FObject(object_order => 2)
  3. BObject(object_order => 3)
  4. AObject(object_order => NULL)
  5. BObject(object_order => NULL)
  6. CObject(object_order => NULL) ......等等。
  7. 我有这样的代码:

    $properties_for_map = array(
        'post_type' => 'property',
        'posts_per_page' => -1,
        'meta_key' => 'object_order',
        'orderby' => 'meta_value_num title',
        'order' => 'ASC',
        'tax_query' => $tax_query
    );
    

    但它只显示带有元键的帖子.. 我试图在网站上找到答案,并找到了一些例子,但并不十分了解它们。也许有人可以帮助我并解释这种方法。

    更新1: 它可以这样做吗?

    $properties_for_map = array(
        'post_type' => 'property',
        'posts_per_page' => -1,
            'meta_query'  => array(
        'relation' => 'OR',
        array(
            'key'     => object_order,
            'compare' => 'EXISTS',
        ),
        array(
            array(
                'key'   => object_order,
                'compare' => 'NOT EXISTS',
            ),
        ),
    ),
             'orderby' => array( 'meta_value_num' => 'ASC', 'title' => 'ASC' ),
        'tax_query' => $tax_query
    );
    

1 个答案:

答案 0 :(得分:0)

我能够获取我所有的帖子,并首先使用元值对它们进行排序,然后按标题将不包含元值的其余帖子排序。

$args = array(
        'post_type'        => 'your-post-type',
        'posts_per_page'   => 20,
        'offset'           => 0,
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'key' => 'your-custom-field-key',
                'compare' => 'EXISTS'
            ),
            array(
                'key' => 'your-custom-field-key',
                'compare' => 'NOT EXISTS'
            )
        ),
        'orderby' => 'meta_value_num title',
        'order' => 'ASC',
    );