0

I have custom post type of brand and custom field generated via types plugin, wpcf-sorter trying to manually create a field to sort my posts. Some of the posts have this custom field populated with a numeric value and others don't have it at all since we're developing this mid-way.

My code is:

$args = array(
  'post_type'      => 'brand',
  'posts_per_page' => 999,
  'meta_key'       => 'wpcf-sorter',
  'orderby'        => 'meta_value_num',
  'order'          => 'DESC'
);

This will pull out all the posts that have the wpcf-sorter meta key. Is there a way to pull every post and if it has the wpcf-sorter, show them first?

0

This answer is pretty covering for this I think:

$args = array(
    'post_type'   => 'brand',
    'posts_per_page' => 999,
    'meta_query'  => array(
     'relation' => 'OR',
        array(
           'key'     => 'wpcf-sorter',
           'compare' => 'NOT EXISTS',
        ),
        array(
          'key'     => 'wpcf-sorter',
          'compare' => 'EXISTS',
       ),
    ),
    'orderby' => array( 'meta_value' => 'DESC', 'date' => 'DESC' ),
);

That should give you all posts with wpcf-sorter-value set first, then the rest, both sets ordered by date.

  • Thank you very much, Emil. This is the final version that sorts correctly. code $args = array( 'post_type' => 'brand', 'posts_per_page' => 999, 'meta_query' => array( 'relation' => 'OR', array( 'key' => 'wpcf-sorter', 'compare' => 'NOT EXISTS', ), array( 'key' => 'wpcf-sorter', 'compare' => 'EXISTS', ), ), 'orderby' => array( 'meta_value_num' => 'DESC'), ); code – Sergiu Poenaru Dec 14 '16 at 13:49
  • Much appreciated! – Sergiu Poenaru Dec 14 '16 at 13:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.