1

I have a simple code where I am attaching existing in the library image to a post:

function attachToPost($attachmentId, $postId){
    return wp_update_post(array(
        'ID' => (int)$attachmentId,
        'post_parent' => (int)$postId
    ));
}

The problem is that I can't attach it to a second post. I read in the internet that this is the way that WordPress works, but is there some kind of solution ?

I don't prefer plugins.

2 Answers 2

1

It is not possible to assign multiple parents to the attachment. However, there is an alternative solution. You can use update_post_meta. to store the attachment id to the post and similarly, you can use function get_post_meta. for getting the attachment id.

1
  • 1
    Can you provide an example on how to do this?
    – StR
    Commented Dec 12, 2019 at 13:49
0

What I did was to use set_post_thumbnail( $postId, $attachmentId );. With it, I can have one image attached to many posts.

2
  • 1
    set_post_thumbnail() is clearly for Sets the post thumbnail (featured image) for the given post.
    – Ronny
    Commented Jan 11, 2021 at 16:52
  • Yes, but in my case it doesn't matter, I am using the REST API and what and how I set there as a response is what and how the client uses, which is a React app.
    – gdfgdfg
    Commented Jan 12, 2021 at 7:24

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.