Viewing 3 reply threads
  • Author
    Posts
    • #1666
      sewid
      Member

      Hi,

      I want to build a CPT for simple events. It should be a normal post with an additional event date-field. I want to show the next 5 events in a widget.

      Everything works fine, I created the CPT with a DatePicker-Field, but the entered date is saved using my specified ‘dateFormat’ (in my case ‘dd.mm.yy’). My problem is now, that I can’t order the events using WP_Query, because I would need a timestamp or anything like this, to oder the events by their date.

      So my question is: Can I use the DatePicker-Field to save the entered Event as timestamp or something similar, that I can use for “order by”?

      Best regards,
      Sebastian

    • #1678
      Steve
      Keymaster

      @sewid– Piklist currently does not support this, so you may need to go old school 😉

      Try hooking into save_post, pull the “pretty” date field, convert it and save another field with the unix timestamp. Then sort on that field.

      This thread on WordPress.org has some good ideas and sample code.

      Let us know if this works for you.

    • #1692
      sewid
      Member

      Thanks a lot for this hint. For somebody with the same problem, my solution looks like:

      function sewid_simple_events_add_timestamp_field( $post_id ) {
      	if ( 'sewid_simple_event' != $_POST['post_type'] ) {
      		return;
      	}
      
      	$event_date = $_POST['_post_meta']['event_date'][0];
      
      	if ( ! empty( $event_date ) ) {
      		$datetime = new DateTime( $event_date );
      		update_post_meta( $post_id, 'event_date_timestamp', $datetime->getTimestamp() );
      	}
      
      }
      
      add_action( 'save_post', 'sewid_simple_events_add_timestamp_field' );
    • #2422
      mcmaster
      Member

      Thanks very much for sharing! I made a few tweaks for my own situation and it worked like a charm.

Viewing 3 reply threads
  • The topic ‘DatePicker-Field – save as timestamp?’ is closed to new replies.