Search code examples
wordpresscustom-post-typeadvanced-custom-fields

WordPress meta_query for Custom Post Type with orderby


I'm trying to sort out a WordPress query for a Custom Post Type, but I can't make it work.

The post type is events. An Advanced Custom Fields field called sticky (yes/no) is used for sorting (stickies on top), and another ACF field called glamrock (yes/no) is used to exclude certain posts.

The result is, glamrock gets excluded, but stickies are not sorted.

If I delete the meta_query, sorting works fine, but glamrock posts are included.

$bpb_args = array(
  'numberposts'     => -1,
  'post_type'       => 'events',
  'posts_per_page'  => 100,
  'paged'           => get_query_var( 'paged', true ),
  'meta-key'        => 'sticky',
  'meta_query'      => array(
    array(
      'key'     => 'glamrock',
      'value'   => 'no',
      'compare' => 'IN',
    )
  ),
  'orderby'   => 'meta_value',
  'order'     => 'ASC',
);

$bpb_query = new WP_Query( $bpb_args );

if( $bpb_query->have_posts() ):
  while( $bpb_query->have_posts() ) : $bpb_query->the_post();
  //show post
  endwhile;
endif;

Update:

Unfortunately, meta_value instead of meta_value_num didn't change anything. It still seems to be sorting by date/time.

The Advanced Custom Field type is Radio Buttons.

In addition to the arguments, I also included the loop.


Solution

  • You need to specify only meta_value since your meta-key is non numeric

    'orderby' => 'meta_value'