1

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: https://i.sstatic.net/mVlse.png

2 Answers 2

1

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.

5
  • 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
    Commented Sep 4, 2011 at 18:30
  • 1
    @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
    Commented Sep 4, 2011 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
    Commented Nov 14, 2011 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
    Commented Nov 14, 2011 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
    Commented Nov 15, 2011 at 9:37
6

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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