• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 774
  • Last Modified:

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?

$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); 

Open in new window

0
Refael
Asked:
Refael
  • 4
  • 3
1 Solution
 
Jason C. LevineNo oneCommented:
How is the date stored in meta?  As a string e.g. "01/01/2012"?
0
 
RefaelAuthor Commented:
Hi jason1178,

Thank you. The format is stored like so "4/20/2012".
0
 
RefaelAuthor Commented:
Hi jason1178,
I replied to your question yesterdays . Is there a solution? Can you help?
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Jason C. LevineNo oneCommented:
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.
0
 
RefaelAuthor Commented:
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?
0
 
Jason C. LevineNo oneCommented:
Switch to 10 digit dates.  

04/20/2012
0
 
RefaelAuthor Commented:
Hi Jason1178
Thank you. i simply changed the format to "d.m.y" and it solved it.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now