Reputation: 2338
I'm attempting to grab only the images from a page in Wordpress.
I read there was a function called get_post_gallery()
but it doesn't seem to obtain my images. This is what I did:
if ( get_post_gallery() ) :
$images = get_post_gallery(get_the_ID(), false);
foreach($images as $image)
{
echo $image['src'];
}
endif;
This line of code is put inside the loop
from what I understand like so:
if ( have_posts() ) {
\\Bit of code in here
}
However, the array that it returns appears to be empty (even though there are images in the post page editor). Do you guys suggest this way or another way to retrieve only images from a post/page?
Upvotes: 0
Views: 104
Reputation: 4774
I've found your answer in another SO question.
Here it is:
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 );
$output .= '<a class="selector thumb" href="' . esc_url( wp_get_attachment_url( $id ) ) . '" title="' . esc_attr( $title ) . '">';
$output .= '<img class="aligncenter" src="' . esc_url( $img[0] ) . '" alt="' . esc_attr( $title ) . '" title="' . esc_attr( $title ) . '" />';
$output .= '</a>';
endforeach;
return $output;
}
Upvotes: 1