简体   繁体   中英

serialize with add_post_meta

i am using cmb2 plugin to create a grouped custom meta boxes for a custom post type. everything from that side is working fine.

i have also created a custom form in the front end to update the custom post type in it's entirety.

the problem which i am having is that my grouped custom meta boxes are not getting updated.

if i check the database after i updated the custom post type from the admin area, the meta_value in the database appears as:

a:3:{s:4:"name";s:4:"tony";s:3:"dob";s:10:"11/02/1982";s:10:"occupation";s:6:"driver";}

but when i updated the custom post type from the front end using the custom form, the meta_value in the database appears as:

s:87:"a:3:{s:4:"name";s:4:"tony";s:3:"dob";s:10:"11/02/1982";s:10:"occupation";s:6:"driver";}";

for some reason the bit of data in the beginning:

s:87:"

is added when i serialize the data array and is causing my data not to be displayed in the admin area on post edit screen.

below is the code which i have used to update the custom post type from the front end:

$current_user = wp_get_current_user();
$pid = get_page_by_title( $current_user->user_email,'OBJECT','application');

$post = array(
            'ID'    => $pid->ID,
            'post_title'    => $current_user->user_email,
            'post_status'   => 'pending',
            'post_type'     => 'application',
            'author'        => $current_user->ID
        );
        $pid = wp_update_post($post);
    }

    foreach($_POST as $k => $v){
        if(is_array($v)){
            delete_post_meta($pid, $k);
            foreach($v as $k2 => $v2){
                add_post_meta($pid, $k, serialize($v2));
            }
        }else{
            update_post_meta($pid, $k, esc_attr(strip_tags($v)));
        }
    }

replace:

add_post_meta($pid, $k, serialize($v2));

with:

add_post_meta($pid, $k, $v2);

i found out that add_post_meta function already serializes the data, therefore i didn't need to use serialize() which was serializing the data again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM