Custom order for Mysql array

I have a Page of Posts, each post has a Custom Field “expired” which contains a date in the format YYYY-MM-DD which is used to order the posts. This date is used for a script that tells the visitor if an offer has either expired or is valid for X days more.

My array is as follows:

Read More
$postid = get_the_ID();
$meta1 = get_post_meta($postid, 'shop', true);
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;

$args = array(
'post_type' => 'post',
'meta_query' => array(
    array(
        'key' => 'shop',
        'value' => $meta1
    )
),
'paged' => $paged,
'posts_per_page' => '4',
'meta_key' => 'expired',
'orderby' => 'meta_value',
'order' => 'ASC'
);

$query = new WP_Query( $args );

This orders the posts using the meta_value of “expired”, earliest date at the top.

When the “expired” meta_value date is before ‘TODAY’ the post script will show “EXPIRED”

When the “expired” meta_value date is after ‘TODAY’ the script will show “Expires in X days”

How posts currently display:

When a post ‘expires’ it currently stays at the top of the post list.

Post 1: Expired
Post 2: Expired
Post 3: Expires in 3 days
Post 4: Expires in 4 days
Post 5: Expires in 6 days

Instead, I’d like to automatically order it thus: (note Post # for comparison to above)

Post 3: Expires in 3 days
Post 4: Expires in 4 days
Post 5: Expires in 6 days
Post 2: Expired
Post 1: Expired

How can I create a custom order where once a post expires (ie. it’s ‘expired’ date is before Today’s date) it is put to the back of the post list yet still above older expired posts?

Thank you.

Related posts

Leave a Reply

1 comment

  1. At first glance, I would think your query isn’t correct. Are you echoing out the variables to make sure they are correct? If you are setting

    'post_per_page' => 4
    

    and you are getting 5 posts, then something seems a bit off. Where it is a number, I believe you can leave off the quotes around it. If that doesn’t fix it, I would echo out $meta1 to make sure that is querying correctly, then I would even try

    'order' => 'DESC'