Skip to content

Instantly share code, notes, and snippets.

@trey8611
Created December 3, 2020 20:51
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trey8611/e4387ba156d6ae6674bdc82bb24fb1a7 to your computer and use it in GitHub Desktop.
Save trey8611/e4387ba156d6ae6674bdc82bb24fb1a7 to your computer and use it in GitHub Desktop.
WP All Import | Check if images exist/are downloadable before trying to download them.

If you provide an image URL that's invalid or that's not available to the server, it can take a while for WP All Import to fail when attempting to download it. To get around this, you can pass your images to a function (see https://www.wpallimport.com/documentation/developers/custom-code/inline-php/) like this:

[my_output_imgs(array({img1[1]},{img2[1]},{img3[1]}))]

Then, use PHP to test them before outputting them in the import template:

function my_output_imgs( $imgs ) {
	foreach ( $imgs as $key => $img ) {
		if ( ! my_check_if_img_exists( $img ) ) {
			unset( $imgs[ $key ] );
		}
	}
	return implode( ',', $imgs );
}
// check if img exists
function my_check_if_img_exists( $url ) {
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_URL,$url );
    // don't download content
    curl_setopt( $ch, CURLOPT_NOBODY, 1 );
    curl_setopt( $ch, CURLOPT_FAILONERROR, 1 );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
	curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 3 );
	curl_setopt( $ch, CURLOPT_TIMEOUT, 7 );

    $result = curl_exec( $ch);
    curl_close( $ch);
    if( $result !== FALSE ) {
        return true;
    } else {
        return false;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment