Comment puis-je enregistrer un état de case à cocher dans une méta-boîte personnalisée WordPress ?

Publié par Jean-Michel le

J’ai écrit le code suivant, mais cela ne sauvera pas l’état. La case à cocher redevient toujours cochée :

<?php

/*META BOXES*/
function add_film_meta_boxes() {
add_meta_box('film_meta_data', 'Film info:', 'film_meta_box_callback', 'film', 'advanced', 'high');
}

function film_meta_box_callback( $post ) {
wp_nonce_field('save_film_meta_data', 'spanish_meta_box_nonce');
$spanish = get_post_meta( $post->ID, '_spanish_value_key', true);

echo '<label>Subtitles: </label>';
$spanish_subtitle_field = get_post_meta($post->ID, 'spanish_subtitle_field', true);
if($spanish_subtitle_field == "yes") {$spanish_subtitle_checked = 'checked="checked"';} else {$spanish_subtitle_checked = '';}

echo '<label><input type="checkbox" id="spanish_subtitle_field" name="spanish_subtitle_field" value="yes" '.$spanish_subtitle_checked.' /></label><label for="spanish_subtitle_field" style="font-weight:normal !important;">spanish &nbsp;</label>';
}

function save_film_meta_data ($post_id) {
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
    return;
if ( ! current_user_can( 'edit_post', $post_id ))
    return;
if( ! isset($_POST['spanish_meta_box_nonce']) )
    return;
if ( ! wp_verify_nonce($_POST['spanish_meta_box_nonce'], 'save_film_meta_data') )
    return;
if ( ! isset( $_POST['spanish_subtitle_field']))
    return;
$spanish = isset($_POST['spanish_subtitle_field']) ? 'on' : 'off';
update_post_meta($post_id, '_spanish_value_key', $spanish);
}
?>

Le code est inclus dans mon fichier functions.php.

Solution n°1 trouvée

Cette ligne est fausse, cela donne à votre metabox une valeur ‘on’ ou ‘off’.

$spanish = isset($_POST['spanish_subtitle_field']) ? 'on' : 'off';

Et lorsque vous vérifiez si est coché, vous recherchez une valeur « oui ».

if($spanish_subtitle_field == "yes") {$spanish_subtitle_checked = 'checked="checked"';} else {$spanish_subtitle_checked = '';}

Essayez donc cette nouvelle fonction et vérifiez si elle fonctionne :

function save_film_meta_data($post_id){
  if(! isset($_POST['spanish_meta_box_nonce'])){
    return;
  }
  if(!wp_verify_nonce($_POST['spanish_meta_box_nonce'],'save_film_meta_data')){
    return;
  }
  if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE){
    return;
  }
  if(! current_user_can('edit_post',$post_id)){
    return;
  }
  if( ! isset($_POST['spanish_subtitle_field'])){
    return;
  }
  $my_data = isset($_POST['spanish_subtitle_field']) ? $_POST['spanish_subtitle_field'] : 'no';
  update_post_meta($post_id,'_spanish_value_key',$my_data);

}

Catégories : Wordpress

Jean-Michel

Jean-Michel est en charge de la partie blog du site. Il met en place la stratégie de contenu et répond aux questions fréquentes sur Wordpress.

0 commentaire

Laisser un commentaire

Avatar placeholder

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *