• I’m trying to create an events calender. On the homepage I’d like to show two upcoming events. To do this I created a meta called ‘_eventdate’ (in functions.php):

    function evenementendetails() {
    	global $post;
    
    	echo '<input type="hidden" name="eventmeta_noncename" id="eventmeta_noncename" value="' .
    	wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
    
    	$eventdate = get_post_meta($post->ID, '_eventdate', true);
    	echo '<p><input type="text" name="_eventdate" placeholder="dd-mm-jjjj" value="' . $eventdate  . '" class="widefat" /></p>';
    }
    
    function wpt_save_events_meta($post_id, $post) {
    
    	if ( !wp_verify_nonce( $_POST['eventmeta_noncename'], plugin_basename(__FILE__) )) {
    	return $post->ID;
    	}
    
    	if ( !current_user_can( 'edit_post', $post->ID ))
    		return $post->ID;
    
    	$events_meta['_eventdate'] = $_POST['_eventdate'];
    
    	foreach ($events_meta as $key => $value) {
    		if( $post->post_type == 'revision' ) return; // Don't store custom data twice
    		$value = implode(',', (array)$value);
    		if(get_post_meta($post->ID, $key, FALSE)) { 			update_post_meta($post->ID, $key, $value);
    		} else {
    			add_post_meta($post->ID, $key, $value);
    		}
    		if(!$value) delete_post_meta($post->ID, $key);
    	}
    
    }
    
    add_action('save_post', 'wpt_save_events_meta', 1, 2);

    On the homepage (front-page.php) I’ve added the following WPQuery code:

    $events = new WP_Query(array(
                'posts_per_page' => '2',
                'post_type' => 'events',
                'orderby' => 'meta_value_num',
                'order' => 'ASC',
                'meta_key' => '_eventdate'
            ));

    Since the user enters the eventdate as “22-02-2016” I convert it to a more readable (dutch) standard: “22 February 2016”:

    $myDateTime = DateTime::createFromFormat('d-m-Y', get_post_meta($post->ID, '_eventdate', true));
    		$newDateString = $myDateTime->format('j F Y');

    I know that the meta_key sorts the _eventdate on the “22-02-2016” version the date. Which of course in my current WP_Query code sorts it on just the day. Which results in a incorrect sorting (First: 8 January 2016, Then: 10 June 2016 and 22 February). I think it is solvabele by converting the eventdate a second time to ‘Ymd’. My only question is how and where could I best implement a conversion of the eventdate so that it gives a correct sorting via the meta_key in WP_Query?

  • The topic ‘Sorting custom post on Meta_key’ is closed to new replies.