lundi 17 août 2020

Multiple checkbox in wordpress fires invalid argument for in array when data is still not saved

I'm trying to make multiple checkbox work for custom meta based in language values. I founded this code in another question and works fine except for the first time you run the code when data is not saved yet returns " in_array() expects parameter 2 to be array string given". I suppose it's because add_meta_data() it's not working in the way intended-if postmeta is empty- but I don't see why or how to make it work. Thanks in advance.

function futbol_meta_box( $post ) {
// Get post meta value using the key from our save function in the second paramater.
$futbol_meta = get_post_meta($post->ID, '_futbol-meta-box', true);

?>
    <input type="checkbox" name="futbol-meta-box[]" value="en" <?php echo (in_array('en', $futbol_meta)) ? 'checked="checked"' : ''; ?> />Inglés
    <br>
    <input type="checkbox" name="futbol-meta-box[]" value="fr" <?php echo (in_array('fr', $futbol_meta)) ? 'checked="checked"' : ''; ?> />Francés
    <br>
    <input type="checkbox" name="futbol-meta-box[]" value="es" <?php echo (in_array('es', $futbol_meta)) ? 'checked="checked"' : ''; ?> />Español<br>
<?php}

add_action( 'save_post', 'save_futbol_meta_box' );
function save_futbol_meta_box() {

global $post;
// Get our form field
if(isset( $_POST['futbol-meta-box'] )) {
    $futbol = $_POST['futbol-meta-box'];
    $old_meta = get_post_meta($post->ID, '_futbol-meta-box', true);
    // Update post meta
    if(!empty($old_meta)){
        update_post_meta($post->ID, '_futbol-meta-box', $futbol);
    } else {
        add_post_meta($post->ID, '_futbol-meta-box', $futbol, true);
    } 
} }



Aucun commentaire:

Enregistrer un commentaire