How to use WordPress update_post_meta with JSON string?

I have this WooCommerce shop that I have to integrate with an external stock system. Therefore I need to create/update products through PHP/WordPress. This part i have figured out.
Problem is the product variations. They are stored in the database as JSON strings.

Example:

Read More
a:1:{s:10:"size";a:6:{s:4:"name";s:10:"Size";s:5:"value";s:17:"42";s:8:"position";s:1:"0";s:10:"is_visible";i:1;s:12:"is_variation";i:1;s:11:"is_taxonomy";i:0;}}

However, when i insert it like this

update_post_meta($product_id, '_product_attributes', 'a:1:{s:10:"size....');

It adds s:173:" a:1:{s:10:"siz.... ";

I have tried with json_encode() which removes the “s:173” but keeps the double quotes at the beginning and end.

Any help on how to store this JSON string without the additional stuff? Would be much appreciated

Related posts

Leave a Reply

2 comments

  1. What you’re seeing in the database is a serialised array. The post meta functions handle all of this for you.

    Use get_post_meta to get the array and simply pass in the array to update_post_meta.

    You don’t need to use serialize / unserialize functions.

  2. I have found some code in woocommerce plugin,

    You can do something like this:-

    $attributes['size'] = array(
        'name'          => "Size",
        'value'         => "42",
        'position'      => "0",
        'is_visible'    => 1,
        'is_variation'  => 1,
        'is_taxonomy'   => 0
    );
    
    update_post_meta( $post_id, '_product_attributes', $attributes );
    

    Hope this help you…