1

I'm trying to grab the image id's of attached images to a post. I'm using an example posted here, but am having trouble returning the just the ids and not the entire array.

My goal is to return a comma separated list of ids of attached images.

1, 2, 3, 4, 5

Here is my function:

function wpse_get_images() {
    global $post;
    $id = intval( $post->ID );
    $size = 'medium';
    $attachments = get_children( array(
        'post_parent'    => $id,
        'post_status'    => 'inherit',
        'post_type'      => 'attachment',
        'post_mime_type' => 'image',
        'order'          => 'ASC',
        'orderby'        => 'menu_order'
    ) );
    if ( empty( $attachments ) )
        return '';

    $output = "\n";

    /**
     * Loop through each attachment
     */
    foreach ( $attachments as $id  => $attachment ) :

        $title   = esc_html( $attachment->post_title, 1 );
        $img     = wp_get_attachment_image_src( $id, $size );
        $imgID   = wp_get_attachment_metadata( $attachment_id );   
        $imgID   = (string)$imgID;
        $output .= $imgID->$attachment_id.', '; // prints: 1,2,3,4,5,6,8,9,         

    endforeach;

    return $output;
}
0

1 Answer 1

1

You can try this one-liner, within the loop, instead of all your above code:

$ids = join( ',', wp_list_pluck( get_attached_media('image' ), 'ID' ) );

where we pluck out the ID's from the get_attached_media() output.

Another approach would be to use:

$ids = join( ',', get_attached_media( '_image_ids' ) );

where we've introduced a new input parameter _image_ids, supported by the use of the following plugin:

/** 
 * Plugin Name: Enhance the get_attached_media() function.
 * Description: Support for the custom '_image_ids' parameter.
 * Plugin URI:  http://wordpress.stackexchange.com/a/169152/26350
 * Author:      birgire
 * Version:     0.0.1
 */
add_filter( 'get_attached_media_args', function( $args, $type, $post ) {
    if( '_image_ids' === $type )
    {
        $args['post_mime_type'] = 'image';
        $args['fields']         = 'ids';
    }
    return $args;
}, 10, 3 );

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.