1

I'm trying to get list of custom posts ordered by numeric meta_key first if such key exist, and than if there is no key, continue order by title.

I mean:

  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) ... and so on.

I have such code:

$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
);

But it only showing post with meta key.. I tried to find an answer on the site, and found some examples, but did not quite understand them. Maybe someone can help me and explain this method.

UPDATE 1: It can be done like this?

$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
);
Denis Kirin
  • 11
  • 1
  • 4
  • Looks good imho. You can always look at `$yourQuery->request` to see the actual SQL, I still find that more straightforward to read than WP_Query parameters. – janh Oct 09 '17 at 20:29
  • Related: https://wordpress.stackexchange.com/questions/102447/sort-on-meta-value-but-include-posts-that-dont-have-one – Blackbam Mar 14 '18 at 15:21

1 Answers1

0

I was able to get all my post and sort them with the meta value first then order the rest of the post without meta value by their title.

$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',
    );
fabian
  • 21
  • 3