Show first posts with custom field not empty and order all by title

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!

Topic order custom-field query custom-post-types Wordpress

Category Web


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

You can order posts by meta value check out the codex

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

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.