Nisam
Nisam

Reputation: 2285

order by custom field in wordpress

I have custom field (date) in my wordpress site, that contain a value like this june 16,2013. How can i treat this field this as date and sort?. Is there any way to sort posts by custon_field date?

I tried in my php page with this code,

$args = array(
 'orderby' => 'meta_value', 
 'order' => 'ASC',
 'meta_key' =>'release_date'
);
query_posts($args); 

it's getting data in sort order, but not based on date, the field is considered as string not date, how can I treated this as date ?

Upvotes: 0

Views: 2000

Answers (3)

Mithun Sreedharan
Mithun Sreedharan

Reputation: 51292

Try

$args = array(
 'orderby' => "DATE_FORMAT(STR_TO_DATE(meta_value, '%M %d,%Y'), '%Y-%m-%d')", 
 'order' => 'ASC',
 'meta_key' =>'release_date'
);
query_posts($args); 

Upvotes: 3

Moeed Farooqui
Moeed Farooqui

Reputation: 3622

Try this:

$date = get_post_meta($post->ID, 'link_banner', true); 
$date_convert = strtotime($date);
$args = array(
 'orderby' => 'meta_value', 
 'order' => 'ASC',
 'meta_key' =>$date_convert 
);
query_posts($args);

Upvotes: 0

php_nub_qq
php_nub_qq

Reputation: 16055

You can set all dates you want to sort in an array and convert them using strtotime(), then simply use sort(). There might be a more efficient way.

Upvotes: 0

Related Questions