If you want to get the actual images inside the post content, you can match them using a regular expression.
To get just the images URLs and dimensions your code can be something like this:
if( is_single() ) {
global $post;
// Match the image URLs inside the post content
$pattern = '/<img.*src="([^"]+)"[^>]*>/';
$matches = [];
preg_match_all( $pattern, $post->post_content, $matches );
// Start looping if there are matches
foreach ( $matches[1] as $url ) {
// Remove the size portion from image URL to get the full size URL
$url = preg_replace( '/(\-[0-9]+x[0-9]+)(.*)$/i', "$2", $url );
// calculate the image dimensions
$image_dimensions = getimagesize($url);
// Do whatever you want here...
}
}
But, if you need to get the WP_Post object of the attachment, you have to convert the image URLs to its post ID using attachment_url_to_postid then get the WP_Post from it; your code may be something like this:
if( is_single() ) {
global $post;
// Match the image URLs inside the post content
$pattern = '/<img.*src="([^"]+)"[^>]*>/';
$matches = [];
preg_match_all( $pattern, $post->post_content, $matches );
// Start looping if there are matches
foreach ( $matches[1] as $url ) {
// Remove the size portion from image URL to get the full size URL
$url = preg_replace( '/(\-[0-9]+x[0-9]+)(.*)$/i', "$2", $url );
// Convert the image URL to the corresponding post ID
$attachment_id = attachment_url_to_postid( $url );
// Get the WP_Post object for the attachment
$attachment = get_post( $attachment_id );
// Do whatever you want here...
}
}
Another way to get the post ID of the inserted image is to match the HTML class of the image. WordPress ads a class “wp-image-{attachmentid}” to every inserted image through the editor where {attachmentid} is the post ID of the inserted image.
So, your code may be something like this:
if( is_single() ) {
global $post;
// Match the attachments IDs inside the post content
$pattern = '/<img.+wp\-image\-([0-9]+)[^>]+>/';
$matches = [];
preg_match_all( $pattern, $post->post_content, $matches );
// Start looping in the found matches
foreach ( $matches[1] as $attachment_id ) {
// Get the WP_Post object for the attachment
$attachment = get_post( $attachment_id );
// Do whatever you want here...
}
}