Support

Account

Home Forums Backend Issues (wp-admin) Gallery – serialized data on update_post_meta

Solved

Gallery – serialized data on update_post_meta

  • Hi,

    I’m using a simple function to duplicate and copy all meta data from existing post to a new one, or

    $post_meta = get_post_meta( $post_id );
                    if( $post_meta ) {
    
                        foreach ( $post_meta as $meta_key => $meta_values ) {
    
                            if( '_wp_old_slug' == $meta_key ) { // do nothing for this meta key
                                continue;
                            }
    
                            foreach ( $meta_values as $meta_value ) {
                                add_post_meta( $new_post_id, $meta_key, $meta_value );
                            }
                        }
                    }

    This works fine for all of the fields except the Gallery field. Somehow, the duplicated data for the Gallery field remain serialized in MySQL, so the gallery images are not loaded in the post admin.

    Below is meta_value from the original post and the duplicated one.

    Original
    a:7:{i:0;s:5:”39281″;i:1;s:5:”39280″;i:2;s:5:”39284″;i:3;s:5:”39282″;i:4;s:5:”39285″;i:5;s:5:”39283″;i:6;s:5:”39286″;}

    Duplicated – serialized
    s:118:”a:7:{i:0;s:5:”39281″;i:1;s:5:”39280″;i:2;s:5:”39284″;i:3;s:5:”39282″;i:4;s:5:”39285″;i:5;s:5:”39283″;i:6;s:5:”39286″;}”;

    What could be the issue and solution to this?

  • You are getting double serialization when updating. The reason why is that get_post_meta( $post_id ) does not universalize the data the way it would if you wanted to get a specific meta field get_post_meta( $post_id, $key ).

    So you need to maybe_unserialze the value before updating.

    
    add_post_meta( $new_post_id, $meta_key, maybe_unserialize($meta_value));
    
Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.