Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I just want to add custom post, a thumbnail of it and custom fields.
Here is my code what I am try is to add post, thumbnail and one custom field. But I not getting the idea how to upload the thumbnail of this specific post. And also how retrieve this post.

$image_url = $_FILES['post_img']['name'];
$tags = $_POST['post_tags'];
$my_post = array(
  //'post_mime_type' => $wp_filetype['type'],
  'post_title'    => wp_strip_all_tags( $_POST['post_title'] ),
  'post_content'  => $_POST['post_content'],
  'post_status'   => 'publish',
  'post_type'     => 'Custamize_post',
  'tags_input'    => array('thread_tag' => $tags),
  'post_author'   => $user_ID
);
$post_link = $_POST['post_link'];


add_post_meta($post_id, 'post_link', $post_link, true); 

I see on some articles they use this code to upload the file.

$upload_dir = wp_upload_dir();
//$image_data = file_get_contents($image_url);
$filename = basename($image_url);
if(wp_mkdir_p($upload_dir['path']))
    $file = $upload_dir['path'] . '/' . $filename;
else
    $file = $upload_dir['basedir'] . '/' . $filename;
file_put_contents($file, $image_url);

$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
    'post_mime_type' => $wp_filetype['type'],
    'post_title' => 'Custamize_post',
    'post_content' => '',
    'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $file, $post_id );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );

set_post_thumbnail( $post_id, $attach_id );

But my main concern here is how to connect the post, created above, to this attachment.

share|improve this question

1 Answer 1

You can do this by setting the post_parent with the $attach_id.

$my_post = array(
    'ID' => $attach_id,
    'post_parent' => $my_post_id //retrieved after you inserted your post
);

wp_update_post( $my_post );

Just run this after you have both the ID`s of the Post and the attachment, and you have set the parent of the attachment to be the post.

share|improve this answer
    
and how can i retive the these attachment because i am not able to get the image which i uploaded. i retrive other data but not attachment. so please tell me how i get all my data. –  Adi Feb 24 '13 at 12:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.