Separate attachment images from post loop

The best way to assign images to a given post is to just upload them in the WordPress post editing/new post area. You can also delete images from there.

With that said, here would be how you do that. You’re going to hook into wp_enqueue_script, and call wp_enqueue_script to add your gallery script to the page. Then you’ll use wp_localize_script, which will print out a nice javascript object for you right above your script.

Inside your hooked function, you access to the $post variable, which contains the current post. You don’t need to be inside the loop to get that. And if you have that, you can get child posts (like attachments), which makes getting images outside the loop very easy.

<?php
add_action( 'wp_enqueue_scripts', 'wpse20321_enqueue_scripts' );
function wpse20321_enqueue_scripts()
{
    // If this isn't a singular post, return -- don't enqueue anything
    if( ! is_singular() ) return;

    // enqueue your gallery script
    wp_enqueue_script( 
        'wpse20321-gallery-script', 
        trailingslashit( get_stylesheet_directory_uri() ) . 'path/to/gallery.js', 
        // use trailingslashit( plugin_dir_url( __FILE__ ) ) . 'path/to/gallery.js' if you're in a plugin
        array( 'jquery' )
    );

    // now we'll get the attachments...
    global $post;
    if( empty( $post ) ) $post = get_queried_object();
    $attachments = get_posts(
        array(
            'post_type'         => 'attachment',
            'post_mime_type'    => 'image',
            'post_status'       => 'inherit',
            'post_parent'       => $post->ID
        )
    );
    if( ! $attachments ) return;
    $out = array();
    $out['img_list'] = array();
    foreach( $attachments as $a )
    {
        $img = wp_get_attachment_image_src( $a->ID, 'full' );
        $out['img_list'][] = array( 
            'image'     => $img[0],
            'width'     => $img[1],
            'height'    => $img[2]
        );
    }

    // call wp_localize_script, which will spit out a nice JSON for you,
    // right before your enqueued gallery script, ready for use.
    // the object name will be wpse20321
    wp_localize_script( 
        'wpse20321-gallery-script', 
        'wpse20321',
        $out 
    );
}

You can add anything you need to that JS object. Want the title attribute saved for the image?

foreach( $attachments as $a )
    {
        $img = wp_get_attachment_image_src( $a->ID, 'full' );
        $out['img_list'][] = array( 
            'image'     => $img[0],
            'width'     => $img[1],
            'height'    => $img[2],
            'title'     => $a->post_title
        );
    }

Leave a Comment