Support

Account

Home Forums General Issues Get posts by ACF if not exists

Helping

Get posts by ACF if not exists

  • Hi there,

    I need to get all custom post type (news) sorted by a custom field true/false named “is_featured”.
    I need to get all posts where “is_features” is set to true, and then the other news sorted by date.

    I’ve tried the following code, but it doesn’t work because the field is new, and it doesn’t exists on old posts.

    
    $new_args = [
    
        'post_type'      => 'news',
        'post_status'    => 'publish',
        'fields'         => 'ids',
        'posts_per_page' => '5',
        'meta_key'       => 'is_featured',
        'orderby'        => 'meta_value_num',
        'order'          => 'desc'
    ];  
    $news = new WP_Query($new_args);
    
    

    How can i fix this?
    Thank you

  • you’ve specified a meta key, but not a value

    
    $new_args = [
    
        'post_type'      => 'news',
        'post_status'    => 'publish',
        'fields'         => 'ids',
        'posts_per_page' => '5',
        'meta_key'       => 'is_featured',
        'meta_value'     => '1',
        'orderby'        => 'meta_value_num', // not sure that this does
        'order'          => 'desc'
    ];  
    $news = new WP_Query($new_args);
    

    Either that or you need to use a meta_query parameter. https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters. You need to test for the value and you need to test that the value exists. See the “compare” argument.

    
      'meta_query' => array(
        array(
          'key' => 'is_featured',
          'compare' => 'EXISTS'
        ),
        array(
          'key' => 'is_featured',
          'value' => '1'
        ),
      ),
    
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Get posts by ACF if not exists’ is closed to new replies.