0

I have a requirement where I need to show all posts having thumbnail first and ordered by title and then remaining posts ordered by title Below is the code I tried

$the_page = (get_query_var('paged')) ? get_query_var('paged') : -1;
    $args = array(
        'post_type' => "listings",
        'post_status' => 'publish',
        //'meta_key' => '_thumbnail_id',
        'order' => 'DESC',
        'posts_per_page' => 88,
        'paged' => $the_page,

        'orderby' => 'meta_key title',
    'meta_query' => array(  //query post based on meta key
        array(
            'relation' => 'OR', // add condition if meta key is exists or not
            array(
                'key' => '_thumbnail_id', 
                'compare' => 'NOT EXISTS' // include post without _thumbnail_id key
            ),
            array(
                'key' => '_thumbnail_id', 
                'compare' => 'NOT NULL' // include post without _thumbnail_id key
            )
        )
    )

If we look closely , I have set orderby='meta_key title' and meta_key is not one of supported arguments in WP_Query Documnentation hence its being removed by WP_Query while generating sql.

In generated sql only ORDER BY wp_posts.post_title DESC is generated.

My question is: 1. do we have any other way to get posts with thumbnail first in the list ? 2. do we have a way to order result by field that is not listed in WP_Query supported arguments list ?

Any help or hint is appreciated :)

Thanks in advance.

  • why not just do a query with orderby' => 'title' and then use an if statement (if (the_post_thumbnail)) to separate the results into 2 different arrays. Now just foreach through the array that has thumbnails, then the array that doesn't. Or put the results in a variable ($thumbs, $nothumbs) and then echo out each variable – rudtek Aug 23 at 15:46
  • @rudtek, thanks for the input but this won't work with pagination I guess.Post with thumb will be there on each page on top this way and not on first page all together. – Dashrath Aug 26 at 14:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.