add_post_meta()
云策文档标注
概述
add_post_meta() 函数用于向指定文章添加自定义字段(元数据)。它处理元数据的存储逻辑,包括数据类型转换、唯一性控制,并确保元数据添加到文章而非修订版本。
关键要点
- 函数参数包括 $post_id(文章ID,必填)、$meta_key(元键名,必填)、$meta_value(元值,必填,支持数组和对象序列化存储)和 $unique(可选,默认为 false,控制是否允许重复键)。
- 返回值:成功时返回 Meta ID,失败时返回 false。
- 元数据在数据库中存储时,布尔值和数字会转换为字符串;非标量数据需可序列化。
- 如果 $unique 为 false 且键已存在,会添加新字段而非更新;更新现有键值应使用 update_post_meta()。
- 元值会经过 stripslashes() 处理,需注意字符转义问题,可参考 update_post_meta() 文档。
- 函数内部调用 add_metadata(),并自动处理文章修订版,确保元数据添加到正确文章。
代码示例
// 添加一个自定义字段,键为 'color',值为 'blue',允许重复键
add_post_meta( 123, 'color', 'blue' );
// 添加唯一自定义字段,键为 '_hidden_key',值为 'secret',不会在后台显示
add_post_meta( 456, '_hidden_key', 'secret', true );注意事项
- 元键以 "_" 开头时,不会在文章编辑屏幕或 the_meta() 中显示,可用于插件或主题的隐藏字段。
- 元值为数组时,即使键不以 "_" 开头,也不会在编辑屏幕显示。
- 使用前应检查文章是否存在,避免无效操作。
原文内容
Adds a meta field to the given post.
Description
Post meta data is called “Custom Fields” on the Administration Screen.
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 name.
$meta_valuemixedrequired-
Metadata value. Arrays and objects are stored as serialized data and will be returned as the same type when retrieved. Other data types will be stored as strings in the database:
- false is stored and retrieved as an empty string (
'') - true is stored and retrieved as
'1' - numbers (both integer and float) are stored and retrieved as strings Must be serializable if non-scalar.
- false is stored and retrieved as an empty string (
$uniquebooloptional-
Whether the same key should not be added.
Default:
false
Source
function add_post_meta( $post_id, $meta_key, $meta_value, $unique = false ) {
// Make sure meta is added to the post, not a revision.
$the_post = wp_is_post_revision( $post_id );
if ( $the_post ) {
$post_id = $the_post;
}
return add_metadata( 'post', $post_id, $meta_key, $meta_value, $unique );
}
Changelog
| Version | Description |
|---|---|
| 1.5.0 | Introduced. |
Skip to note 6 content
Codex
Hidden Custom Fields
If you are a plugin or theme developer and you are planning to use custom fields to store parameters related to your plugin or template, it is interesting to note that WordPress will not show custom fields which have keys starting with an “_” (underscore) in the custom fields list on the post edit screen or when using the
the_meta()template function. This can be for example used to show these custom fields in an unusual way by using theadd_meta_box()function.The following example:
will add a unique custom field with the key name
_colorand the value ‘red’ but this custom field will not display in the post edit screen.In addition, if the
$meta_valueargument is an array, it will not be displayed on the page edit screen, even if you don’t prefix the key name with an underscore.Skip to note 7 content
Codex
Adding or Updating a Unique Custom Field
Adds a new custom field if the key does not already exist, or updates the value of the custom field with that key otherwise.
</pre> </div><!-- .comment-content --> <section id='feedback-465' class='wporg-has-embedded-code feedback hide-if-js' data-comment-count='2'> <ul class='children'> <li id="comment-3139" data-comment-id="3139" class="comment byuser comment-author-ravanh odd alt depth-2"> <article id="div-comment-3139" class="comment-body"> <div class="wporg-has-embedded-code comment-content" id="comment-content-3139"> <div>Just <code>update_post_meta ( 7, 'fruit', 'banana' );</code> alone does the same.</div> <div><a href="https://profiles.wordpress.org/ravanh/" rel="external nofollow" class="url">Rolf Allard van Hagen</a> <a class="comment-date" href="https://developer.wordpress.org/reference/functions/add_post_meta/#comment-3139"><time datetime="2019-04-08T22:59:12+00:00">7 years ago</time></a></div> </div><!-- .comment-content --> </article> </li> <li id="comment-5756" data-comment-id="5756" class="comment byuser comment-author-capbussat even depth-2"> <article id="div-comment-5756" class="comment-body"> <div class="wporg-has-embedded-code comment-content" id="comment-content-5756"> <div>In some cases I prefer extra checks like checking if is empty and then delete it. <code>delete_post_meta($post_id, $meta_key, $meta_value); </code></div> <div><a href="https://profiles.wordpress.org/capbussat/" rel="external nofollow" class="url">capbussat</a> <a class="comment-date" href="https://developer.wordpress.org/reference/functions/add_post_meta/#comment-5756"><time datetime="2022-04-01T08:24:31+00:00">4 years ago</time></a></div> </div><!-- .comment-content --> </article> </li> </ul> </section><!-- .feedback --> <footer class='feedback-links wporg-dot-link-list' > <a role="button" class="feedback-login" href="https://login.wordpress.org/?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Ffunctions%2Fadd_post_meta%2F%3Freplytocom%3D465%23feedback-editor-465" rel="nofollow">Log in to add feedback</a></footer> </article><!-- .comment-body --> </li> <li id="comment-466" data-comment-id="466" class="comment byuser comment-author-codex odd alt thread-odd thread-alt depth-1"> <article id="div-comment-466" class="comment-body"> <a href="#comment-content-466" class="screen-reader-text">Skip to note 8 content</a> <header class="comment-meta"> <div class="comment-author vcard"> <span class="comment-author-attribution"> <a href="https://profiles.wordpress.org/codex/" rel="external nofollow" class="url">Codex</a> </span> <a class="comment-date" href="https://developer.wordpress.org/reference/functions/add_post_meta/#comment-466"> <time datetime="2015-07-02T08:31:32+00:00"> 11 years ago </time> </a> </div> <div class="user-note-voting" data-nonce="c173a0159d" data-can-vote="false"><a class="user-note-voting-up" title="You must log in to vote on the helpfulness of this note" data-id="466" data-vote="up" href="https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Ffunctions%2Fadd_post_meta%2F%23comment-466"><span class="screen-reader-text">You must log in to vote on the helpfulness of this note</span></a><span class="user-note-voting-count " title="100% like this"><span class="screen-reader-text">Vote results for this note: </span>1</span><a class="user-note-voting-down" title="You must log in to vote on the helpfulness of this note" data-id="466" data-vote="down" href="https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Ffunctions%2Fadd_post_meta%2F%23comment-466"><span class="screen-reader-text">You must log in to vote on the helpfulness of this note</span></a></div> </header> <!-- .comment-metadata --> <div class="wporg-has-embedded-code comment-content" id="comment-content-466"> <p><strong>Other Examples</strong><br /> Adds a new custom field only if a custom field with the given key does not already exists:</p> <pre class="wp-block-code"><code lang="php" class="language-php ">Adds several custom fields with different values but with the same key ‘my_key’:
For a more detailed example, see the post_meta Functions Examples page.
Skip to note 9 content
Codex
Default Usage
Skip to note 10 content
capbussat
I prefer a more complete solution which checks if is empty and deletes it:
function my_update_post_meta($post_id, $meta_key, $new_meta_value)
{
$meta_value = get_post_meta($post_id, $meta_key, true);
if ($new_meta_value && ” === $meta_value)
add_post_meta($post_id, $meta_key, $new_meta_value, true); // unique
else if ($new_meta_value && $new_meta_value !== $meta_value)
update_post_meta($post_id, $meta_key, $new_meta_value, $meta_value);
// same prev_value
else if (” === $new_meta_value && $meta_value)
delete_post_meta($post_id, $meta_key, $meta_value); }