I have this problem with attaching images and add media.

ADD MEDIA

  1. Go to page
  2. Click on “Add media”
  3. Insert an image
  4. Image shows in editor, but when I go to the page and do the below code it doesn’t update.

ATTACH IMAGE

  1. Go to media
  2. find image and attach a page
  3. This works ok, but once that image is attached to that page I cannot attach it to another

CODE

 $attachments = get_attached_media( 'image', $page_id);

$images = array();
foreach ($attachments as $attachment) 
{   
            $image = wp_get_attachment_url($attachment->ID);
            if($image)
                $images[] = $image;
}

wp_localize_script( 'custom-js-script', 'images', $images);

1. I want to use add media because I can then I can re-use images on different pages BUT IT DOESN’T WORK how can I get the images as the above code?

2. If I can’t do the above how can I re-use attachments?

1 Answer
1

Why:

In WordPress one can only attach a file to a single parent post. This is because the relationship is stored in the wp_post table as the post_parent field. It’s a bigint(20) type so it can only contain a single number (ID).

Workaround:

We would need to cook something ourselves, maybe that could be by using a custom taxonomy for our attachments or perhaps using custom fields (post meta) to store the attachments IDs?

Or we could try some plugins out there that can help us re-using our attachments.

Leave a Reply

Your email address will not be published. Required fields are marked *