0

New to WordPress (and PHP) and am trying to get this PHP snippet to work with the Code Snippets plugin so I can display all media attachments within my post. It is working, in that it shows the attachments as thumbnails on the post now, but because the print_r function is used they are appearing at the top of the page instead of where the shortcode is placed. I know to fix this the return statement must be used but I can't figure out how to return the data correctly. If I use the return statement it just prints the text 'Array' to the page. Can someone please help me understand how this should be adjusted so that this function returns the data necessary to display the media? I'm assuming each attachment must be added to an array and then the contents of that array printed but I can't figure out how to do it. Thanks.

function get_media () {
    $attachments = get_posts( array(
            'post_type'   => 'attachment',
            'numberposts' => -1,
            'post_status' => null,
            'post_parent' => get_the_ID()
        ) );
 foreach ( $attachments as $attachment ) {
               print_r(wp_get_attachment_image( $attachment->ID, 'thumbnail' ));
            }
}

add_shortcode( 'media', 'get_media' ) ;

1 Answer 1

2

The problem with your code, as you mentioned, is that you are outputting the images via your print_r function, and you need to instead build a string to return, which is displayed in place of the shortcode.

Give this a try:

function get_media () {
    $attachments = get_posts([
            'post_type'   => 'attachment',
            'numberposts' => -1,
            'post_status' => null,
            'post_parent' => get_the_ID()
    ]);
    
    if ($attachments) {
        foreach ($attachments as $attachment) {
            $output .= wp_get_attachment_image($attachment->ID);
        }
    }

    return $output;
}

add_shortcode( 'media', 'get_media' ) ;

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.