add_meta()
云策文档标注
概述
add_meta() 函数用于为指定文章添加元数据,数据来源于 $_POST 超全局变量,通常用于处理“自定义字段”表单提交。它根据输入选择元键,并调用 add_post_meta() 实现存储。
关键要点
- 参数 $post_id 为整数类型,必需,指定文章 ID
- 返回值类型为 int|bool,成功时返回元 ID,失败返回 false
- 元数据从 $_POST['metakeyselect']、$_POST['metakeyinput'] 和 $_POST['metavalue'] 获取
- 元键优先使用输入字段(metakeyinput),若两者都存在则忽略选择字段(metakeyselect)
- 函数会检查元键是否受保护(is_protected_meta)和用户权限(current_user_can)
- 内部使用 wp_unslash 和 wp_slash 处理字符串转义
代码示例
add_meta( $post_ID );注意事项
除非开发了使用自定义字段小部件的自定义文章表单,否则很少直接使用此函数。
原文内容
Adds post meta data defined in the $_POST superglobal for a post with given ID.
Parameters
$post_idintrequired
Source
function add_meta( $post_id ) {
$post_id = (int) $post_id;
$metakeyselect = isset( $_POST['metakeyselect'] ) ? wp_unslash( trim( $_POST['metakeyselect'] ) ) : '';
$metakeyinput = isset( $_POST['metakeyinput'] ) ? wp_unslash( trim( $_POST['metakeyinput'] ) ) : '';
$metavalue = isset( $_POST['metavalue'] ) ? $_POST['metavalue'] : '';
if ( is_string( $metavalue ) ) {
$metavalue = trim( $metavalue );
}
if ( ( ( '#NONE#' !== $metakeyselect ) && ! empty( $metakeyselect ) ) || ! empty( $metakeyinput ) ) {
/*
* We have a key/value pair. If both the select and the input
* for the key have data, the input takes precedence.
*/
if ( '#NONE#' !== $metakeyselect ) {
$metakey = $metakeyselect;
}
if ( $metakeyinput ) {
$metakey = $metakeyinput; // Default.
}
if ( is_protected_meta( $metakey, 'post' ) || ! current_user_can( 'add_post_meta', $post_id, $metakey ) ) {
return false;
}
$metakey = wp_slash( $metakey );
return add_post_meta( $post_id, $metakey, $metavalue );
}
return false;
}
Changelog
| Version | Description |
|---|---|
| 1.2.0 | Introduced. |
Skip to note 2 content
Codex
Example
/* * Unless you developed a custom post form that uses the custom field widget, * there is little reason to use this function */ add_meta( $post_ID );