Support

Account

Home Forums General Issues Filter Custom Post Type by ACF Date Picker Field Reply To: Filter Custom Post Type by ACF Date Picker Field

  • I had searched the forums for “filter by date picker” and only found this post: (http://support.advancedcustomfields.com/forums/topic/filtering-cpt-with-date-picker-custom-field/) that seemed like it might be somewhat helpful at first but I cannot make sense of it.

    I did try the example code on the Date Picker Field Documentation page, as a starting point, but I was getting this error on the events page: Fatal error: Call to undefined method DateTime::createfromformat()

    After much hair pulling I see that I mistakenly thought I was running PHP 5.3.24 (on my hosting) but today remembered this particular site is on different hosting (the client’s hosting) and their server is running PHP 5.2.6.

    So now I’ve attempted this code (from the Date Picker docs page, referring to PHP versions less than 2.3) and all it outputs is “01/01/1970January 1 1970”. 🙁

    <?php get_header(); ?>
    
    <?php 
    /*
    *  Create PHP DateTime object from Date Piker Value
    *  The ACF "Workaround" for PHP 5.2 as shown in the docs
    */
    $date = get_field('event_end-date'); // $date = 19881123 (23/11/1988)
     
    // extract Y,M,D
    $y = substr($date, 0, 4);
    $m = substr($date, 4, 2);
    $d = substr($date, 6, 2);
     
    // create UNIX
    $time = strtotime("{$d}-{$m}-{$y}");
     
    // format date (23/11/1988)
    echo date('d/m/Y', $time);
     
    // format date (November 11th 1988)
    echo date('F n Y', $time);
     
    /* Order Posts based on Date Picker value */
    $posts = get_posts(array(
    	'post_type' => 'event', // name of custom post type
    	'meta_key' => 'event_end-date', // name of custom field
    	'orderby' => 'meta_value_num',
    	'order' => 'ASC'
    ));
     
    if( $posts )
    {
    	foreach( $posts as $post )
    	{
    		setup_postdata( $post );
     
    		echo 'hello?';
    
    	}
    	wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly
    }
      
    ?>
    <?php get_footer(); ?>