我正在学习创建一个元框来上传文件wp-content/uploads
通过以下代码创建文件夹:
//display image meta box
function display_image_box() {
global $post;
wp_nonce_field( plugin_basename( __FILE__ ), \'wp_custom_noncename\' );
echo \'<input id="post_media" type="file" name="post_media" value="" size="25" />\';
}
//upload image
function update_custom_meta_data( $id, $data_key, $is_file = false ) {
if( $is_file && ! empty( $_FILES ) ) {
$upload = wp_handle_upload( $_FILES[$data_key], array( \'test_form\' => false ) );
if( isset( $upload[\'error\'] ) && \'0\' != $upload[\'error\'] ) {
wp_die( \'There was an error uploading your file. \' );
} else {
update_post_meta( $id, $data_key, $upload );
}
}
}
//save image
function save_custom_meta_data( $id ) {
if( ! wp_verify_nonce( $_POST[\'wp_custom_noncename\'], plugin_basename( __FILE__ ) ) ) {
return;
}
if( defined( \'DOING_AUTOSAVE\' ) && DOING_AUTOSAVE ) {
return;
}
update_custom_meta_data( $id, \'post_media\', true );
}
add_action( \'save_post\', \'save_custom_meta_data\' );
//register script
function register_admin_scripts() {
wp_register_script( \'custom_admin_script\', get_template_directory_uri() . \'/js/admin.js\' );
wp_enqueue_script( \'custom_admin_script\' );
}
add_action( \'admin_enqueue_scripts\', \'register_admin_scripts\' );
这很有效,文件上传很好,但我无法显示它,因为我得到的数组如下所示:
[post_media] => Array
(
[0] => a:3:{s:4:"file";s:81:"E:wampwwwtestchild/wp-content/themes/twentyeleven/uploads/2012/12/coffee_star.jpg";s:3:"url";s:60:"wp-content/themes/twentyeleven/image/2012/12/coffee_star.jpg";s:4:"type";s:10:"image/jpeg";}
)
如何在模板中显示图像
此外,如何保存URL(
wp-content/themes/twentyeleven/image/2012/12/coffee_star.jpg
) 仅作为元数据?
最合适的回答,由SO网友:Ralf912 整理而成
你为什么不看看你得到的答案?In this answer 我让你用get_post_meta
而不是get_post_custom
. 原因很简单:get_post_meta( post_id, metakey, single )
返回单个值,如果single
设置为true
(RTFM!!)
如果你想使用get_post_meta()
, 你就会得到你的答案。如果没有,请尝试unserialize()