create custom field and upload image in wordpress

孤街浪徒 提交于 2019-12-07 18:44:58

问题


i'm trying to learn the way for uploading image file through custom field but cant get the easiest code to do it. i just done a bit here:

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) 

anybody please take me to next step and show the way to display the image in blog page too.


回答1:


Lets go Stepwise here:

  1. Create custom field Meta Box for inserting Image Url in post type => post.
  2. Update/Save the custom field value in back end.
  3. Display the custom field value in front end.

Seeing your code it seems that you are missing #2. Try the code below to save custom field:

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');

Code for #3 that displaying the custom field will be:

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



回答2:


you could try wrap it in wp_get_attachment_url like this:-

wp_get_attachment_url( $custom_image["custom_field_image"][0] ); 


来源:https://stackoverflow.com/questions/13776444/create-custom-field-and-upload-image-in-wordpress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!