wordpressimage-upload

create custom field and upload image in wordpress


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.


Solution

  • 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] ?>" />