Search code examples
phpwordpresssortingdatecustom-post-type

wordpress get_posts ordered by custom field which is a custom date


i have a custom post type for members and the birth date is saved like 01.01.2013

$args = array(
    'numberposts'   => -1,
    'post_type'       => 'mitglied',
    'post_status'     => 'publish',
    'meta_key'      => 'geburtsdatum',
    'meta_value'    => date("d.m.Y"),
    'meta_compare' => '>',
    'orderby' => 'meta_value',
    'order' => 'ASC'
);
$geburtstage = get_posts ( $args );

i want a list with the birthdays of the members ordered by month and day like this

  • 4th of january, person 10
  • 8th of march, person 2
  • ...
  • 1st of december, person 3

with the code above the list is ordered by day

  • 1st of december, person 3
  • 4th of january, person 10
  • 8th of march, person 2

also important is, that the ordering is not influenced by the year of birth


Solution

  • I think my task is not solveable with get_posts only, so i did it in 3 steps.

    First, i used get_posts to get all members

    $args = array(
        'numberposts'   => -1,
        'post_type'       => 'mitglied',
    );
    $geburtstage = get_posts ( $args );
    

    Then filled an array with the data. For sorting I made a timestamp with the day and month of the birthday, but the actual year. Although with this solution it would not have been necessary, I changed the date format to yyyy-mm-dd. @barakadam explained in his answer to my question how to do this. I use the wordpress plugin Advanced Custom Fields, so I fetch the custom fields with get_field()

    $mitglieder = array( array() );
    $i = 0;
    foreach($geburtstage as $post){
        setup_postdata( $post );
    
        $datum = explode( "-",get_field('geburtsdatum') );
    
        $mitglieder[$i]['orderby'] = mktime(0, 0, 0, (int)$datum[1], (int)$datum[2], date('Y'));
        $mitglieder[$i]['name'] = get_field( 'name' );
        $i++;
    }
    

    The last step is using array_multisort to get the intended order

    foreach ($mitglieder as $key => $row) {
        $dates[$key] = $row['orderby'];
    }
    array_multisort($dates, SORT_ASC, $mitglieder);
    

    Thanks to @barakadam and @Christopher for participating.