Originally my goal was to compress my code, now after I altered it, it is not working anymore. I can't figure out why. I simplified it a bit, now this code should save one date entered in the backend in a custom meta box of a custom post type but apparently the update_post_meta()
function is not working anymore. E.g. if I select a date and save the post, the change isn't saving.
add_action ('admin_init', 'cpt_event_meta_fields');
add_action ('save_post', 'cpt_event_save_data');
function cpt_event_meta_fields() {
add_meta_box("event-meta-1", "Datum (von)", "cpt_event_callback", "Termin", "normal", "high");
}
function cpt_event_callback( $post ) {
$dateStart = get_post_meta( get_the_ID(), 'date-start', true );
echo $dateStart;
echo '<input type="date" name="date-start" value="' . $dateStart . '" />';
}
function cpt_event_save_data() {
global $post;
update_post_meta(get_the_ID(), "date-start", $dateStart);
}
After reviewing the answer below is myupdated code. My main problem was the use of global $post
outside of the Loop. I used global $_POST
instead. Also I now changed the input from date
to text
and sanitized the textfields using sanitize_text_field()
add_action ('admin_init', 'cpt_event_meta_fields');
add_action ('save_post', 'cpt_event_save_data');
function cpt_event_meta_fields() {
add_meta_box("event-meta-1", "Datum (von)", "cpt_event_callback", "Termin", "normal", "high");
add_meta_box("event-meta-2", "Datum (bis)", "cpt_event_2_callback", "Termin", "normal", "high");
}
function cpt_event_callback( $post ) {
$dateStart = get_post_meta( get_the_ID(), 'date-start', true );
echo '<input type="text" name="date-start" value="' . $dateStart . '" />';
}
function cpt_event_2_callback( $post ) {
$dateEnd = get_post_meta( get_the_ID(), 'date-end', true );
echo '<input type="text" name="date-end" value="' . $dateEnd . '" />';
}
function cpt_event_save_data() {
global $_POST;
global $dateStart;
$dateStart = sanitize_text_field($_POST['date-start']);
$dateEnd = sanitize_text_field($_POST['date-end']);
update_post_meta(get_the_ID(), "date-start", $dateStart);
update_post_meta(get_the_ID(), "date-end", $dateEnd);
}