_block_bindings_post_meta_get_value()
云策文档标注
概述
_block_bindings_post_meta_get_value() 是 WordPress 中用于获取文章元数据(Post Meta)源值的函数,主要用于块绑定(Block Bindings)上下文。它通过验证参数、权限和元数据注册状态来安全地检索指定文章元数据。
关键要点
- 函数接受两个参数:$source_args(包含元数据键的数组)和 $block_instance(块实例对象)。
- 返回值为混合类型,表示计算出的源值;在多种验证失败时返回 null。
- 验证包括:检查元数据键是否存在、文章 ID 是否有效、文章是否公开或用户是否有权限访问、元数据是否受保护、以及元数据是否在 REST API 中注册为可显示。
- 最终通过 get_post_meta() 获取并返回元数据值。
代码示例
_block_bindings_post_meta_get_value( array( "key" => "foo" ), $block_instance );注意事项
- 函数在 WordPress 6.5.0 版本中引入。
- 相关函数包括 is_post_publicly_viewable()、get_registered_meta_keys()、post_password_required()、is_protected_meta()、current_user_can()、get_post_meta() 和 get_post()。
原文内容
Gets value for Post Meta source.
Parameters
$source_argsarrayrequired-
Array containing source arguments used to look up the override value.
Example: array( “key” => “foo” ). $block_instanceWP_Blockrequired-
The block instance.
Source
function _block_bindings_post_meta_get_value( array $source_args, $block_instance ) {
if ( empty( $source_args['key'] ) ) {
return null;
}
if ( empty( $block_instance->context['postId'] ) ) {
return null;
}
$post_id = $block_instance->context['postId'];
// If a post isn't public, we need to prevent unauthorized users from accessing the post meta.
$post = get_post( $post_id );
if ( ( ! is_post_publicly_viewable( $post ) && ! current_user_can( 'read_post', $post_id ) ) || post_password_required( $post ) ) {
return null;
}
// Check if the meta field is protected.
if ( is_protected_meta( $source_args['key'], 'post' ) ) {
return null;
}
// Check if the meta field is registered to be shown in REST.
$meta_keys = get_registered_meta_keys( 'post', $block_instance->context['postType'] );
// Add fields registered for all subtypes.
$meta_keys = array_merge( $meta_keys, get_registered_meta_keys( 'post', '' ) );
if ( empty( $meta_keys[ $source_args['key'] ]['show_in_rest'] ) ) {
return null;
}
return get_post_meta( $post_id, $source_args['key'], true );
}
Changelog
| Version | Description |
|---|---|
| 6.5.0 | Introduced. |