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 tried to add an image as Attachment image to a post. in wp_postmeta i added _wp_attached_file as meta_key and value = productimages/Routers/v/CISCO1941.jpg it not works and i could not see the image as attachment! but when i use add image button in wordpress's HTML editor, it add exactly this field to that table but with a different post ID!

is there any dependency for that field? screenshot from db: http://i.stack.imgur.com/mVlse.png

share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

You do not add image attachment to post. In WordPress image attachment is also post. See post types in Codex.

  • what is usually called post on surface is technically post of post post type.

  • image attachment is a post of attachment post type.

So what you need to do is to create image attachment (using wp_insert_attachment() and couple more related functions) and set your post as parent for it.

share|improve this answer
    
Ofcourse you can! He meant to ask adding a independent uploaded image to be attached to a post, just like how you can do it in Media library. –  Ashfame Sep 4 '11 at 18:30
    
@Ashfame that was not how I understood the question, will leave up to Amino to clarify. Anyway my answer does cover how to make it attached - set post as parent for it. –  Rarst Sep 4 '11 at 18:33
    
@Rarst: If i have a post id $post_id and $attachment_id, what is the function to add the parent as $post_id for $attachment_id? –  Sisir Nov 14 '11 at 15:09
    
@Sisir I don't remember if there is function for it. Technically it's post_parent field in posts table that holds ID of parent. –  Rarst Nov 14 '11 at 17:41
    
Hey, I made one :) here it is pastebin.com/nVVE2Bvq You think wordpress should have a function like this? Can we add it to trac? –  Sisir Nov 15 '11 at 9:37
add comment

Like what Rarst mentioned, you technically want to set the attachment's post_parent value to the ID of the post you are attaching it to.

e.g. you can do something like this:

wp_update_post( array(
        'ID' => $attachment_id,
        'post_parent' => $post_id
    )
);

However, please take note of the caution when using wp_update_post.

Another method using $wpdb

global $wpdb;
$wpdb->query(
    "
    UPDATE $wpdb->posts 
    SET post_parent = $post_id
    WHERE ID = $attachment_id
        AND post_type = 'attachment'
    "
);
share|improve this answer
add comment

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.