WordPress – Fetching all data and sorting

I am using WordPress. I have the following query to fetch data from database and it is working perfectly

$args1 = array(
 'post_type' => 'gallery',
 'posts_per_page' => $gnum,
 'post__in' => array(400, 403),
 'paged' => $paged,
 'orderby' => 'title',
 'order' => 'ASC'                    

);

query_posts($args1);

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

//And then some other code to display data

Using 'post__in' => array(400, 403),in the above query I am fetching the rows where ID=’400′ AND ‘403’ . So when I echo, I get to see only two information.

Read More

Now, what I am trying to achieve is to fetch all data from the table but when I display the information I want to get the row where ID is 400 at first then 403 and then rest of the rows based on 'orderby' => 'title', AND ‘order’ => ‘ASC’

Could you please help with the query?

Thanks

Edit

$args2 = array(
 'post_type' => 'gallery',
 'posts_per_page' => $gnum,
 'post__not_in' => array(400, 403),
 'paged' => $paged,
 'orderby' => 'title',
 'order' => 'ASC'                    

);

query_posts($args2);

Related posts

Leave a Reply

3 comments

  1. Not sure if this will work within the query_post argument, but it is supplementing valid SQL in to it. Try:

    $args = array(
     'post_type' => 'gallery',
     'posts_per_page' => $gnum,
     'paged' => $paged,
     'orderby' => 'case when ID in (400,403) then -1 else title end, title',
     'order' => 'ASC'                    
    );
    
    query_posts($args);
    
  2. That is not going to be possible using the WordPress query structure like you are doing. One possible solution is to do a second query looking for results not in (400, 403) and simply add this array of results to the end of your first array.

    In order to do this, you should probably use get_posts() instead of query_posts() so that it doesn’t alter the main loop.

    $array = get_posts($args1);
    $array = array_merge($array, get_posts($args2);
    
  3. I suppose you could try doing the following:

    $args = array(
     'post_type' => 'gallery',
     'posts_per_page' => $gnum,
     'paged' => $paged,
     'orderby' => 'ID = 400 DESC, ID = 403 DESC, title',
     'order' => 'ASC'                    
    );
    
    query_posts($args);
    ...
    

    Let me know how this goes.