WordPress: OrderBY meta_key_value including null value

I am trying to make a simple query in wordpress ordered by a meta_value_num of a custom field.

$args1 = array(
'post_type'         => 'task',
'post_status'       => 'publish',
'meta_key'          => 'task_due_date',  
'orderby'           => 'meta_value_num', 
'order'             => ASC, 
'posts_per_page'    => -1,                                                              
);

I want to include the posts that have the custom field empty or null too ordered first or last in the query. How can I achieve that?

Related posts

Leave a Reply

1 comment

  1. A simple and quick solution:

    <?php
    setup_postdata( $GLOBALS['post'] =& $post );
    
    $posts= get_posts(array(
        'post_type'         => 'task',
        'post_status'       => 'publish',
        'meta_key'          => 'task_due_date',  
        'orderby'           => 'meta_value_num', 
        'order'             => ASC, 
        'posts_per_page'    => -1,                                                              
        ));
    
    if( $posts ):
        foreach( $posts as $post ): ?>      
    
        <!-- HTML HERE -->
    
        <?php endforeach;
        wp_reset_postdata();
    endif; ?>
    ?>
    

    If you want to get the generated SQL just pass it to the WP_Meta_Query object:

    $query_args = array(
        'post_type'         => 'task',
        'post_status'       => 'publish',
        'meta_key'          => 'task_due_date',  
        'orderby'           => 'meta_value_num', 
        'order'             => ASC, 
        'posts_per_page'    => -1,                                                              
        );
    
    $meta_query = new WP_Meta_Query();
    $meta_query->parse_query_vars( $query_args );
    $res = $meta_query->get_sql(
        'task',
        $wpdb->posts,
        'ID',
        null
    );