Reputation: 12882
i'm trying to get all images of a post using this method:
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => $post->ID
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$images[] = wp_get_attachment_image_src( $attachment->ID, ATTACHMENT_IMAGE_SIZE );
}
return $images;
}
unfortunately, this will get all images ever uploaded, not just those associated to the current post. i found this post using *get_children*, but it doesn't work either. any ideas?
ps: i running the code when a post created/updated
Upvotes: 1
Views: 10106
Reputation: 146269
Try it by adding a hook in your functions.php
to fire after post/page has been created/updated and wrap your code inside that function as given bellow
add_action( 'save_post', 'after_post_save' );
function after_post_save( $post_id ) {
if ( 'post' == get_post_type($post_id) ) // check if this is a post
{
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => $post_id
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$images[] = wp_get_attachment_image_src( $attachment->ID, ATTACHMENT_IMAGE_SIZE );
}
return $images; // End of function and nothing happens
}
}
}
Remember, basically it'll do nothing by returning the $images
array at the end of your function unless you do something with the images.
Note: The wp_get_attachment_image_src
function returns an array which contains
[0] => url // the src of image
[1] => width // the width
[2] => height // the height
So in your $images
array it will contain something like this
array(
[0] => array([0] => url, [1] => width, [2] => height), // first image
[1] => array([0] => url, [1] => width, 2] => height) // second image
);
Upvotes: 1
Reputation: 831
You can try
<?php
$attachments = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_parent' => $post->ID,
) );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
$class = "post-attachment mime-" . sanitize_title( $attachment->post_mime_type );
$thumbimg = wp_get_attachment_link( $attachment->ID, 'thumbnail-size', true );
echo '<li class="' . $class . ' data-design-thumbnail">' . $thumbimg . '</li>';
}
}
?>
Read more here.
Make sure $post->ID is not empty. If this is still not working you can try Extracting Images from the Page / Post content. More details here
Upvotes: 4