You are not querying/saving the correct meta_key
. For example, looking at your code, you pass $typename
variable to update_post_meta()
as meta_key
and $typename="events"
. But later in the query you are querying for meta_key = date
. Also, you pass $meta
as meta_value
and in your actual code $meta
is an array containing multiple values (location, date, start, etc).
$typename="events";
//$_POST[$typename] is actually an array
$meta = $_POST[$typename];
......
.....
update_post_meta($id, $typename, $meta);
If you don’t touch the HTML of the meta box, you have to change the saving code and the query. For example:
add_action('save_post', 'events_save_meta');
function events_save_meta($post_id) {
$typename="events";
if ( isset($_POST['post_type']) && 'events' == $_POST['post_type'] ) {
//You may need to change 'edit_post' for the correct capability set when register 'events' post type
if ( !current_user_can( 'edit_post', $post_id ) ) {
return;
}
}
if( !isset( $_POST[$typename . "-nonce"] ) || !wp_verify_nonce($_POST[$typename . "-nonce"], $typename) ) {
return;
}
if( isset($_POST[$typename]['date']) ) {
update_post_meta($post_id, 'date', $_POST[$typename]['date']);
} else {
delete_post_meta($post_id, 'date');
}
}
Now you have a meta field with meta_key = 'date'
and you can query for this meta_key
:
$args = array(
'post_type' => 'events',
'meta_key' => 'date',
'meta_value' => current_time('Ymd'),
'meta_compare' => '>=',
'orderby' => 'meta_value_num',
'order' => 'ASC'
);
$events_query = new WP_Query( $args );