我正在开发我的第一个 WP 插件,但卡住了。
我在内容编辑器下方的帖子页面上创建了一个自定义字段(字段 1)。它保存正确。 :)
添加媒体时,我在媒体库弹出窗口中创建了一个自定义字段(字段 2)。它保存正确。 :)
我想要做的是使用字段 1 的值作为字段 2 的默认值。
我怀疑问题出在 attachment_fields_to_edit 回调函数中。
我认为 $post 现在指的是实际的“文件附件帖子”而不是帖子本身,所以当我引用我保存的值时:
$post_meta = get_post_meta( $post->ID );
它实际上是在提取与该附件相关联的所有元数据,而不是与当前帖子相关联的元数据。是否可以从实际帖子中提取元数据?
此代码来自 Codex:
function my_add_attachment_location_field( $form_fields, $post ) {
$field_value = get_post_meta( $post->ID, 'location', true );
$form_fields['location'] = array(
'value' => $field_value ? $field_value : '',
'label' => __( 'Location' ),
'helps' => __( 'Set a location for this attachment' )
);
return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'my_add_attachment_location_field', 10, 2 );
function my_save_attachment_location( $attachment_id ) {
if ( isset( $_REQUEST['attachments'][$attachment_id]['location'] ) ) {
$location = $_REQUEST['attachments'][$attachment_id]['location'];
update_post_meta( $attachment_id, 'location', $location );
}
}
add_action( 'edit_attachment', 'my_save_attachment_location' );
我如何为我们插入附件的当前帖子获取_post_meta?这需要在上面的 codex 代码中的 my_add_attachment_location_field 回调函数中发生。
谢谢!
最佳答案
我能想到的一种方式:
$actual_post_id = $post->post_parent;
然后你可以这样做:
get_post_meta($actual_post_id)
关于php - WordPress 从回调函数中获取 Post Meta,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22850878/