在WordPress中将字符串保存到数据库

Saving string to database in WordPress

我正在将选项保存到我的数据库中。 JSON 字符串是从 ajax 调用返回的,我正在像

一样对其进行清理
$my_settings = wp_json_encode( sanitize_text_field( wp_unslash( $_POST['data'] ) ) );

当我用 update_option 保存它时,它在数据库中保存为

"{ \"0\": { \"settings\": { \"default\": \"0\", \"header_main_title\": \"\",...

现在如果我只这样做

$my_settings = sanitize_text_field( wp_unslash( $_POST['data'] ) );

数据库中的条目将是

{ "0": { "settings": { "default": "0", "header_main_title": "",...

第二个版本仍然可以使用 json_decode 解码,因为毕竟这是一个 JSON 字符串,并且没有斜线双引号。

困扰我的是:

由于 wpdb update 方法,而不是 sanitize_option,选项值始终保存安全。您可以保存任何您想要的数据。查看 update_option 代码:

$update_args = array(
         'option_value' => $serialized_value,
);
$result = $wpdb->update( $wpdb->options, $update_args ...

Update方法使用prepare,所以总是安全的:

return $this->query( $this->prepare( $sql, $values ) );