0

I have a custom post type called "products". My goal is to make my custom query that I have on homepage and also the search query show first the posts that have a custom field called "id_number" not empty and then the other posts that have the "id_number" empty. All should be ordered by title.

This is my code so far only for my custom query. I also need it for search page query but I didn't get that far.

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $wp_query = new WP_Query( array(
    'post_type' => 'products',
    'posts_per_page' => 20,
    'post_status' => 'publish',
    'pagination' => true,
    'meta_query' => array(
     'relation' => 'OR',
     array( 
           'key' => 'id_number',
           'compare' => 'EXISTS',
                ),
     array( 
          'key' => 'id_number',
           'compare' => 'NOT EXISTS'                
    )
    ),
    'meta_key' => 'id_number',
    'orderby' => 'title',
    'paged'=>$paged
    ) ); 

Any help will be appreciated. Thank you!

0

You can order posts by meta value check out the codex

https://codex.wordpress.org/Class_Reference/WP_Query

  • that's my main issue here, I have to order by title, ordering by value would not be hard at this point and I know how to do it but I just don't need that. – Raul May 7 '16 at 17:52
  • There is option to order by title also – BlueSuiter May 7 '16 at 17:57
  • True but I can't figure out how to keep the posts with empty custom field value first at the same time. – Raul May 7 '16 at 18:05
  • Get all posts in order by title and then separate them in foreach loop, by applying a check if the meta field is empty concate it in different variable and if in case it have value concate it in another variable. After the loop first echo posts with meta field and after that without meta field ones. – BlueSuiter May 8 '16 at 7:08
0

Try this..

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $wp_query = new WP_Query( array(
    'post_type' => 'products',
    'posts_per_page' => 20,
    'post_status' => 'publish',
    'pagination' => true,
    'meta_query' => array(
     'relation' => 'OR',
     'id_number' => array( 
           'key' => 'id_number',
           'compare' => 'EXISTS',
                ),
     'id2_number' => array( 
          'key' => 'id_number',
           'compare' => 'NOT EXISTS'                
    )
    ),
    'meta_key' => 'id_number',
    'orderby' => 'id_number',
    'paged' => $paged
    ) ); 

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.