函数文档

update_post_meta()

💡 云策文档标注

概述

update_post_meta() 函数用于更新指定文章 ID 的元数据字段,若字段不存在则自动添加。它支持通过 $prev_value 参数区分相同键名的多个值,并处理转义和序列化数据。

关键要点

  • 函数基于文章 ID 更新元数据,可替代 add_post_meta() 使用
  • 参数包括 $post_id(必填)、$meta_key(必填)、$meta_value(必填,非标量需可序列化)和 $prev_value(可选,用于指定更新条件)
  • 返回值:元数据不存在时返回 Meta ID,成功更新返回 true,失败或值未变返回 false
  • 历史原因要求输入时元键和元值需“转义”(使用 wp_slash 补偿 stripslashes() 调用)
  • 注意处理 JSON 等包含转义字符的数据,避免存储转义值

代码示例

// 更新页面模板示例
update_post_meta( $page_id, '_wp_page_template', 'new_template.php' );

注意事项

  • 当 $meta_value 与数据库现有值相同时,函数返回 false
  • 若未设置 $prev_value,同一键名的所有值都会被更新
  • 处理序列化数据时需注意数组结构,避免嵌套问题
  • 数据库排序规则为大小写不敏感时,update_post_meta() 可能影响大小写不同的键,但 get_post_meta() 因缓存保持敏感

📄 原文内容

Updates a post meta field based on the given post ID.

Description

Use the $prev_value parameter to differentiate between meta fields with the same key and post ID.

If the meta field for the post does not exist, it will be added and its ID returned.

Can be used in place of add_post_meta() .

For historical reasons both the meta key and the meta value are expected to be “slashed” (slashes escaped) on input.

Parameters

$post_idintrequired
Post ID.
$meta_keystringrequired
Metadata key.
$meta_valuemixedrequired
Metadata value. Must be serializable if non-scalar.
$prev_valuemixedoptional
Previous value to check before updating.
If specified, only update existing metadata entries with this value. Otherwise, update all entries. Default empty.

Return

int|bool Meta ID if the key didn’t exist, true on successful update, false on failure or if the value passed to the function is the same as the one that is already in the database.

More Information

Character Escaping

Post meta values are passed through the stripslashes() function upon being stored, so you will need to be careful when passing in values (such as JSON) that might include escaped characters.

Do not store escaped values

Consider the JSON value {"key":"value with "escaped quotes""}

Workaround

By adding one more level of escaping using function wp_slash (introduced in WP 3.6), you can compensate for the call to stripslashes()

Source

function update_post_meta( $post_id, $meta_key, $meta_value, $prev_value = '' ) {
	// Make sure meta is updated for the post, not for a revision.
	$the_post = wp_is_post_revision( $post_id );
	if ( $the_post ) {
		$post_id = $the_post;
	}

	return update_metadata( 'post', $post_id, $meta_key, $meta_value, $prev_value );
}

Changelog

Version Description
1.5.0 Introduced.

User Contributed Notes

  1. Skip to note 11 content

    ¡IMPORTANT If you are working with serialized data, the array is updated with an extra nested array
    In order to keep the same structure, update the Object in the 1rst nested position.

    $ticket_meta = get_post_meta($azgTorneoID,"mep_event_ticket_type",)
    $ticket_meta[0][0]["option_rsv_t"] = "9";
    update_post_meta($azgTorneoID,"mep_event_ticket_type",$ticket_meta[0]);

  2. Skip to note 12 content

    Other Examples
    Assuming a post has an ID of 76, and the following 4 custom fields:

    [key_1] => 'Happy'
    [key_1] => 'Sad'
    [key_2] => 'Gregory'
    [my_key] => 'Steve'

    To change key_2’s value to Hans:

    To change key_1’s value from Sad to Happy:

    The fields would now look like this:

    [key_1] => 'Happy'
    [key_1] => 'Happy'
    [key_2] => 'Hans'
    [my_key] => 'Steve'

    Note: This function will update only the first field that matches the criteria.

    To change the first key_1’s value from Happy to Excited:

    Edit Page template

    [/php]

    For a more detailed example, go to the post_meta Functions Examples page.

  3. Skip to note 13 content

    Please note that if your database collation is case insensitive (as with suffix _ci) then update_post_meta() and delete_post_meta() and get_posts() will update/delete/query the meta records with keys that are upper or lower case. However get_post_meta() will be case sensitive due to WordPress caching. See https://core.trac.wordpress.org/ticket/18210 for more info.