How to get_posts where 'menu_order' is more than 0/zero?

Is it possible to get posts where menu_order is more than 0? I have tried this argument when I get_posts() but it doesn't have any effect at all:

'meta_query'     = array(
      'key'     = 'menu_order'
    , 'value'   = '0'
    , 'compare' = ''
)

What I'm after in the first place is to treat menu_order 0 as last priority, or "specific menu_order not set" so that if I set a post to 1 or 2 as menu_order. Those posts will be looped out before everyone with 0. I should say, all of this with ASC as orderby of course.

And I can't see any other WordPress-way to do it than have two get_posts() after each other and in the first one exclude all posts with menu_order 0 and in the second only get these ones.

But to do that, I first have to find out how to filter by menu_order. Anyone that knows how to do that?

Topic menu-order order loop get-posts Wordpress

Category Web


Karun's answer made me look more into the posts_where filter to find a better solution to hook into the WP_Query. After a bit more google searching I found this page that did it in a better way.

Using that method I finally got it to work like this:

add_filter('posts_where', function ($where, $query)
{
    global $wpdb;

    $label = $query->query['query_label'] ?? '';

        if ($label === 'ignore_zero_query')
        {   
            $where .= " AND {$wpdb->prefix}posts.menu_order > 0 ";
        }

        if ($label === 'only_zero_query')
        {
            $where .= " AND {$wpdb->prefix}posts.menu_order <= 0 ";
        }

    return $where;

}, 10, 2);

And I now get the posts this way instead:

$args = array(
    'posts_per_page' => -1,
    'query_label'    => 'ignore_zero_query',
    );
$posts_query = new WP_Query();
$posts = $posts_query->query($args);

<?php
function ignore_zero_menu_order( $where ){    
  global $wpdb;
  $where = $where . ' AND $wpdb->posts.menu_order > 0 ';             
  return $where;
}

$args = array(      
    'post_type' => 'page',
    'meta_query'     => array(
        'key'     => 'menu_order',
        'value'   => '0',
        'compare' => '>'
    )
);


add_filter( 'posts_where', 'ignore_zero_menu_order' );
$query = new WP_Query($args);
remove_filter( 'posts_where', 'ignore_zero_menu_order' );

About

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