Can I attach image to post without adding it to post?

Can I “attach” images to a post without adding it to the post?
The reason behind this is so that I can manipulate it however I want using an API.

Related posts

Leave a Reply

3 comments

  1. Yes, its definitely possible: I do this in one of my themes.

    You simply add your images to the post as if you were going to insert it into the post, but then just click save all changes, and do not actually click the button “Insert Into Post”.

    Then, you can access that post’s gallery images using something like:

    $images = get_gallery_images();
    

    where I’ve defined that function in functions.php:

    // get all of the images attached to the current post
        function get_gallery_images() {
            global $post;
            $photos = get_children( array('post_parent' => $post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID') );
            $galleryimages = array();
            if ($photos) {
                foreach ($photos as $photo) {
                    // get the correct image html for the selected size
                    $galleryimages[] = wp_get_attachment_url($photo->ID);
                }
            }
            return $galleryimages;
        }
    

    And then do whatever you’d like to those images in your template files. (In my case, I loop through the images and put them in a jQuery slider).

    There are also plugins that you could use, but its always best to minimise plugins if you can help it.

  2. Yes, you can.

    If you upload the image using the media uploader on a post’s edit screen, or use update_post() to set the post_parent field of the attachment to the ID of the post you want to attach it to, it is associated with that post, whether or not it is actually inserted into the content of that post.

    You can retrieve all images attached to a specific post by calling get_children() (see the codex for examples).