Home>

I have implemented custom field saving using thesave_posthook in WordPress.

If I$_ POSTthe array as this stored value andjson_encode ()it, double quotes will be added, but I want to delete it.

Problem i am experiencing

"[]"is saved in the DB with the following source code.
I want to delete the double quotes and use[].

Applicable source code

The following is written in functions.php.
The custom field keys aretest_array_1andtest_array_2.

test_array_1is[]and[]is stored in the DB, but
test_array_2is going to get[]from$_ POST, but"[]">Is saved.

// Update custom fields
add_action ('save_post', 'my_save_post_meta');
function my_save_post_meta ($post_id) {
    // custom field key
    $meta_keys = ['test_array_1', 'test_array_2'];
    // update
    foreach ($meta_keys as $meta_key) {
        // This is no problem with saving [] regardless of $_POST
        if ($meta_key == 'test_array_1') {
            $test_array_1 = [];
            my_update_post_meta_encode ($post_id, 'test_array_1', $test_array_1);
        }
        // I want to save [] using $_POST, but "[]" is saved
        elseif ($meta_key == 'test_array_2') {
            $test_array_2 = stripslashes ($_POST [$meta_key]);
            my_update_post_meta_encode ($post_id, 'test_array_2', $test_array_2);
        }
    }
}
// encode and save the array
function my_update_post_meta_encode ($id, $cf_key, $val) {
    $encoded = json_encode ($val);
    update_post_meta ($id, $cf_key, $encoded);
    return $encoded;
}

test_array_2saves"[]"in the DB, so we created a function calledmy_trim_doublequote ()that removes double quotes. It was. it's here.

function my_trim_doublequote ($str) {
    $trimed = trim ($str);
    $trimed = ltrim ($trimed, "\" ");
    $trimed = rtrim ($trimed, "\" ");
    return $trimed;
}


Then, usingmy_trim_doublequote ()above, I added it to the corresponding source code as follows, but this did not change and the double quote remained unchanged and"[]"has been saved.

elseif ($meta_key == 'test_array_2') {
            $test_array_2 = my_trim_doublequote (stripslashes ($_POST [$meta_key]));
            my_update_post_meta_encode ($post_id, 'test_array_2', $test_array_2);
        }
Illustration

DB looks like this.

How can I save[]withtest_array_2?

Supplement

The version of WprdPress is 5.2.0.
json_encode ()is mandatory.

  • Answer # 1

    The value of

    $test_array_1is an empty array, while the value of$test_array_2is not an empty array and is called[]String.

    $encoded = json_encode ($val);

    JSON encoded in the upper part, but when$test_array_1,$valis an empty array, so it is JSON encoded andThe string will be [].
    On the other hand, when$test_array_2,$valis a string[], so it is JSON encoded and"[ ] ".

    To solve the problem, either convert the value obtained from$_ POSTfrom a character string to an array and assign it to$test_array_2, or do not encode it with JSON. It is necessary to save it as it is.

Related articles