0

I have a question.

I use the following code to output the image URLs of a wordpress post. The image URLs are related to the "attached images" of a wordpress post and not the ones that are actually used in the post.

If you added an image to a post 2 years ago, but currently don't use the image anymore, the old unused Image Url will still be output via the code. I would like to avoid this.

What i need to do to adjust the code to output only those Image URLs that are really in the source code of the post or really actually used in the post? That can be also Images that are attached to another wordpress post.

<?php
if( is_single() ) {
    global $post;
    $args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_mime_type' => 'image', 'post_status' => null, 'post_parent' => $post->ID ); 
    $attachments = get_posts($args);
    if ($attachments) {
            foreach ( $attachments as $attachment ) {
                    $img_title = $attachment->post_excerpt;
                    $metadata = wp_get_attachment_metadata($attachment->ID);
                    $width = $metadata['width'];
                    $height = $metadata['height'];
                    echo '<meta property="og:image" content="'.$attachment->guid.'"/>';
                    echo '<meta property="og:image:type" content="image/jpeg" />';
                    echo '<meta property="og:image:width" content="'.$width.'"/>';
                    echo '<meta property="og:image:height" content="'.$height.'"/>';
            }
    }
}
?>
1
  • Hi! Can you clarify what you mean 'curently don't use the image anymore' ? Has the image been deleted and so it's 404 now, but the code still shows it? – mozboz Jun 22 '20 at 9:50
0

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...
        
    }
}
0

thanks for your help. I used this variant of your code with a little diffrent preg_replace code. If the Image URL contain numbers like "-510x383.jpg" i had some Problems with your code.

<?php
if( is_single() ) {
    global $post;
    $pattern = '/<img.*src="([^"]+)"[^>]*>/';
    $matches = [];
    preg_match_all( $pattern, $post->post_content, $matches );
    foreach ( $matches[1] as $url ) {
        $clean_url  = preg_replace('/<img .*src=["|\']([^"|\']+)/i', "", $url );
        $https_url  = str_replace("http:", "https:", $clean_url);
        list($width, $height) = getimagesize($https_url);
        echo '<meta property="og:image" content="'.$https_url.'"/>';
        echo '<meta property="og:image:type" content="image/jpeg" />';
        echo '<meta property="og:image:width" content="'.$width.'"/>';
        echo '<meta property="og:image:height" content="'.$height.'"/>';
    }
}
?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.