Aar*_*ron 7 php meta wordpress post
我正在制作我的第一个WP插件,而且卡住了.
我在内容编辑器下面的帖子页面上创建了一个自定义字段(字段1).它保存正确.:)
我在添加媒体时在媒体库弹出窗口中创建了一个自定义字段(字段2).它保存正确.:)
我想要做的是使用字段1中的值作为字段2的默认值.
我怀疑问题在于attachment_fields_to_edit回调函数.
我认为$ post现在指的是实际的"文件附件帖子"而不是帖子本身,所以当我引用我保存的值时:
$post_meta = get_post_meta( $post->ID );
Run Code Online (Sandbox Code Playgroud)
它实际上是拉动与该附件相关联的所有元素,而不是当前帖子.是否可以从实际帖子中提取元数据?
此代码来自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' );
Run Code Online (Sandbox Code Playgroud)
对于我们正在插入附件的当前帖子,我如何get_post_meta?这需要在上面的codex代码中的my_add_attachment_location_field回调函数中进行.
谢谢!
我能想到的一种方法:
$actual_post_id = $post->post_parent;
然后你可以这样做:
get_post_meta($actual_post_id)