How to check if an image attachment exists before uploading

OK I finally found the problem! I was trying to assign the same slug to both the attachment and the parent post, and apparently WordPress won’t have that. The “name” in the media library for the attachment was correct but the actual slug was getting a -2 at the end.

Here’s the fixed code, simply by making the image slugs unique:

// sample vars
$slug = 'my-post-slug';
$card['img'] = 'http://example.com/img1.jpg';
$card['imgGold'] = 'http://example.com/img2.jpg';
// end sample vars

$images="";
$images[] = $card['img'];
$images[] = $card['imgGold'];
foreach ( $images as $url ) {

    // check if current url is for regular or gold image
    if ( $card['imgGold'] == $url ) {
        $desc = $slug .'-img-gold';
    } else {
        $desc = $slug .'-img';
    }

    // check if attachment already exists
    $attachment_args = array(
        'posts_per_page' => 1,
        'post_type'      => 'attachment',
        'name'           => $desc
    );
    $attachment_check = new Wp_Query( $attachment_args );

    // if attachment exists, reuse and update data
    if ( $attachment_check->have_posts() ) {

        echo 'Attachment <strong>'. $desc .'</strong> found, omitting download...<br>';

        // do stuff..

    // if attachment doesn't exist fetch it from url and save it
    } else {

        echo 'Attachment <strong>'. $desc .'</strong> not found, downloading...<br>';

        // handle image upload from url and assign to post
        $src = media_sideload_image( $url, $post_id, $desc, 'src' );

        // add post meta
        if ( $card['imgGold'] == $url  ) {
            add_post_meta( $post_id, 'imgGold', $src );
        } else {
            add_post_meta( $post_id, 'img', $src );
        }

    } // end attachment exists

} // end foreach image

Leave a Comment

error code: 523