$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>post meta - Show future events based on custom field AND order by date|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

post meta - Show future events based on custom field AND order by date

matteradmin9PV0评论

I have a custom content type (event), within that type I have a custom date field, with the name: 'date'. In my template I am running the WP_Query to return a list of events. I would like to only get events that are in the future (according to my custom 'date' field) and then order the list by that same field.

I have tried the following but it simply returns a list of all the 'events' in the system, regardless of date

$today = date('d M, y');

$args = array (
    'post_type'              => 'event',
    'meta_query'             => array(
        array(
            'key'       => 'date',
            'value'     => $today,
            'compare'   => '>',
            'type'      => 'CHAR',
        ),
    ),
    'meta_key'               => 'date',
    'orderby'                => 'meta_value_num',
    'order'                  => 'ASC'
);

As a note: if I replace the type from 'CHAR' to 'DATE' I get no results returned...

I have a custom content type (event), within that type I have a custom date field, with the name: 'date'. In my template I am running the WP_Query to return a list of events. I would like to only get events that are in the future (according to my custom 'date' field) and then order the list by that same field.

I have tried the following but it simply returns a list of all the 'events' in the system, regardless of date

$today = date('d M, y');

$args = array (
    'post_type'              => 'event',
    'meta_query'             => array(
        array(
            'key'       => 'date',
            'value'     => $today,
            'compare'   => '>',
            'type'      => 'CHAR',
        ),
    ),
    'meta_key'               => 'date',
    'orderby'                => 'meta_value_num',
    'order'                  => 'ASC'
);

As a note: if I replace the type from 'CHAR' to 'DATE' I get no results returned...

Share Improve this question asked Feb 8, 2014 at 17:41 KevKev 1871 gold badge4 silver badges10 bronze badges 7
  • How is your date stored in the database? – s_ha_dum Commented Feb 8, 2014 at 17:44
  • I am using a plugin to create the custom fields but I specified the same date format as the one listed for the $today variable... – Kev Commented Feb 8, 2014 at 17:47
  • I have just double checked and an example date in the database is: 14 Feb, 14 – Kev Commented Feb 8, 2014 at 18:19
  • 1 your date format is meaningless to MySQL, you need to store it as numeric yyyy-mm-dd to be able to query and order on it correctly. – Milo Commented Feb 8, 2014 at 18:21
  • Ah ok, so do I need to do that at the point of data entry or can I convert it through php? – Kev Commented Feb 8, 2014 at 18:32
 |  Show 2 more comments

4 Answers 4

Reset to default 3

I found the actual issue so I thought I'd update.

ACF documentation says to use $today = date ('Ymd') to compare dates but you really need to use current_time('Ymd') so I removed the functions.php code that I added and fixed the problem rather than work around it.

Here's my query now

$event1 = current_time('Ymd');
    $args = array(
        'post_type' => 'events',
    'post_status' => 'publish',
    'posts_per_page' => '10',
    'meta_query' => array(
        array(
            'key' => 'event_date_ends',
            'compare' => '>=',
            'value' => $event1,
            )
            ),
    'meta_key' => 'event_date_ends',
    'orderby' => 'meta_value',
    'order' => 'ASC',
    'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1 ),
);

So for your query try this

$today = current_time('d M, y');

$args = array (
    'post_type'              => 'event',
    'meta_query'             => array(
        array(
            'key'       => 'date',
            'value'     => $today,
            'compare'   => '>=',
        ),
    ),
    'meta_key'               => 'date',
    'orderby'                => 'meta_value',
    'order'                  => 'ASC'
);

Just make sure the current_time ('d M, y') is how you have your data being stored via whatever date picker you're using or if you're typing it in each event in a field that's how you're typing it in. d M, y would read 19 Jun, 14. Remember your display date and stored date can read differently. I hope this helps.

Here's what I did. I am using the Advance Custom Fields plugin for the custom fields. I followed the instructions here: http://wordpress/support/topic/plugin-advanced-custom-fields-sorting-by-date-picker, which states the easiest way to do this is to compare dates in unix timestamp format.

My date field in ACF is called: event_start
The date is being saved in my database in yymmdd format
I have the Custom Post Type: events

Step 1 is to create the Start Date Field in ACF.
Step 2 is to add this function to your functions.php (assuming PHP > 5.3) This function takes my human readable front-end input and converts to Unix timestamp and saves it in another post meta row.

function custom_unixtimesamp ( $post_id ) {
  if ( get_post_type( $post_id ) == 'events' ) {
    $startdate = get_post_meta($post_id, 'event_start', true);
    if($startdate) {
        $newdate = DateTime::createFromFormat('Ymd', $startdate)->getTimestamp();
        update_post_meta($post_id, 'unixstartdate', $newdate  );
    }
  }
}
add_action( 'save_post', 'custom_unixtimesamp', 100, 2);

Step 3, now you can sort and compare on the Unix Timestamp

$today = time();            
$args = array(
    'post_type' => 'events',
    'posts_per_page' => '50',
    'meta_query' => array(
        array(
            'key' => 'unixstartdate',
            'compare' => '>=',
            'value' => $today,
        )
    ),
    'meta_key'=>'event_start',  
    'orderby' => 'meta_value_num',
    'order' => 'ASC'
);
$wp_query = new WP_Query( $args );

Marc's suggestion was pretty close.

Here's what worked for me and you can try too.

functions.php

function custom_unixtimesamp ( $post_id ) {
    if ( get_post_type( $post_id ) == 'events' ) {
    $startdate = get_post_meta($post_id, 'event_date_begins', true);

        if($startdate) {
            $dateparts = explode('/', $startdate);
            $newdate1 = strtotime(date('d.m.Y H:i:s', strtotime($dateparts[1].'/'.$dateparts[0].'/'.$dateparts[2])));
            update_post_meta($post_id, 'unixstartdate', $newdate1  );
        }
    }
}
add_action( 'save_post', 'custom_unixtimesamp', 100, 2);

then query

$today = time();    

    $args = array(
        'post_type' => 'events',
    'post_status' => 'publish',
    'posts_per_page' => '10',
    'meta_query' => array(
        array(
            'key' => 'unixstartdate',
            'compare' => '>=',
            'value' => $today,
            )
            ),
    'meta_key' => 'event_date_begins',
    'orderby' => 'meta_value',
    'order' => 'ASC',
    'paged' => ( get_query_var('paged') ? get_query_var('paged') : 1 ),
);

You don't need to worry about putting anything into your functions.php file, or saving timestamps, etc. All you need to do is add the correct 'type' value into your meta_query array, to let it know that you are comparing dates. So the value of 'type' sould be "DATE"...

Eg...

$today = current_time('Y-m-d');

$args = array (
    'post_type'              => 'event',
    'meta_query'             => array(
        array(
            'key'       => 'event_date',
            'value'     => $today,
            'compare'   => '>=',
            'type'      => 'DATE',
        ),
    ),
    'meta_key'               => 'event_date',
    'orderby'                => 'meta_value',
    'order'                  => 'ASC'
);

...In this example, my date-storing meta field is called 'event_date' and I am checking for entries with dates in the future (or today).

Post a comment

comment list (0)

  1. No comments so far