0

I'm working with the new media manager, and have a little issue to retrieve the attachment of the post. I'm developing a plugin which needs to retrieve all attachments of specific posts.

I first thought of using the following code :

   $args = array( 
        'post_type' => 'attachment', 
        'numberposts' => -1, 
        'post_status' => 'inherit', 
        'post_parent' => $id ); 
    $attachments = get_posts($args);

The issue though, is that this will retrieve the attachment that I have uploaded in this specific post, not the one I current use.

For example let's say I have three posts. When I created the first post I've directly uploaded all the images that I would need for the three posts, but only use some of them for the actual post as ACF or gallery. The issue is that when I run the above code, I will have an array with all attachments of the three posts when searching attachments for my first post, and none when searching attachments for the second and third posts. Even though I'm using some images for these last posts.

So does anyone have an idea how I can retrieve all the images actually used in a post and not the images that have been attached to this post?

1 Answer 1

0

I'm guessing you'll need to fetch the post content and parse it using something like this as a guide (pasted code from above link for future reference).

// Get the all post content in a variable
$posttext = $post->post_content;
$posttext1 = $post->post_content;

// search for the src="" in the post content
$regular_expression = '~src="[^"]*"~';
$regular_expression1 = '~<img [^\>]*\ />~';

// grab all the images from the post in an array $allpics using preg_match_all
preg_match_all( $regular_expression, $posttext, $allpics );

// Count the number of images found.
$NumberOfPics = count($allpics[0]);

// This time we replace/remove the images from the content
$only_post_text = preg_replace( $regular_expression1, '' , $posttext1);

// Check to see if we have at least one image
if ( $NumberOfPics > 0 )
{
/* profit */
}
1
  • Ok, This is I didn't really wanted to do this, because I have some custom fields created with ACF containing images. I guess I'll just go through all the custom fields I've created and retrieve the url I need ! Thanks for your answer though Commented May 19, 2013 at 14:42

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.