Refael
asked on
WordPress sort posts by custom field
Hello Experts,
I am trying to sort WP posts by a custom filed which is a date field.
For some reason it does not work. Can anyone help please?
I am trying to sort WP posts by a custom filed which is a date field.
For some reason it does not work. Can anyone help please?
$parent_id = $posts[0]->ID;
$args=array(
'post_parent' => $parent_id,
'post_type' => 'page',
'post_status' => 'publish',
'posts_per_page' => -1,
'caller_get_posts'=> 1 ,
'order'=> 'ASC',
'orderby'=>'meta_value&meta_key=past_event_date'
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();
$event_date = get_post_meta($post->ID, 'event_date', true);
$display_event_date = date('dS F Y', strtotime(get_post_meta($post->ID, "event_date", true)));
$event_title = get_post_meta($post->ID, 'event_title', true);
How is the date stored in meta? As a string e.g. "01/01/2012"?
ASKER
Hi jason1178,
Thank you. The format is stored like so "4/20/2012".
Thank you. The format is stored like so "4/20/2012".
ASKER
Hi jason1178,
I replied to your question yesterdays . Is there a solution? Can you help?
I replied to your question yesterdays . Is there a solution? Can you help?
That format can't be sorted like a string would be and if these are stored in meta, they are simple strings.
10/1/2099 would come before 4/20/2012 because of the leading 1. You either need to format the dates differently so they sort better or switch up what you are doing so you write dates to a date data type.
10/1/2099 would come before 4/20/2012 because of the leading 1. You either need to format the dates differently so they sort better or switch up what you are doing so you write dates to a date data type.
ASKER
Hi jason1178,
Can you give me an example? is there a way to print the date in this format but let it sort in the format it stores in the database?
Can you give me an example? is there a way to print the date in this format but let it sort in the format it stores in the database?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Hi Jason1178
Thank you. i simply changed the format to "d.m.y" and it solved it.
Thank you. i simply changed the format to "d.m.y" and it solved it.