在wordpress中创建自定义字段并上传图片

meh*_*oha 2 wordpress image-upload

我正在尝试学习通过自定义字段上传图像文件的方式,但无法获得最简单的代码。我只是在这里做了一点:

add_action('admin_init', 'create_image_box');
function create_image_box() {
add_meta_box( 'meta-box-id', 'Image Field', 'display_image_box', 'post', 'normal', 'high' );
}

//Display the image_box
function display_image_box() {
 global $post;
  $image_id = get_post_meta($post->ID,'xxxx_image', true);
 echo 'Upload an image: <input type="file" name="xxxx_image" id="xxxx_image" />';

// Upload done: show it now...(as thmbnail or 60 x 50) 
Run Code Online (Sandbox Code Playgroud)

任何人都请带我进入下一步并展示在博客页面中显示图像的方式。

小智 6

让我们逐步在这里:

  1. 创建自定义字段元框,用于在帖子类型 => 帖子中插入图像网址。
  2. 在后端更新/保存自定义字段值。
  3. 在前端显示自定义字段值。

看到你的代码,你似乎错过了#2。试试下面的代码来保存自定义字段:

function save_joe_details($post_id){
  global $post;
  if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
  return $post_id;
  update_post_meta($post->ID, "custom_field_image", $_POST["custom_field_image"] );
}
add_action('save_post', 'save_joe_details');
Run Code Online (Sandbox Code Playgroud)

显示自定义字段的 #3 代码将是:

<?php global $post;
$custom_image = get_post_custom($post->ID); ?>
<img src="<?php echo $custom_image["custom_field_image"][0] ?>" />
Run Code Online (Sandbox Code Playgroud)