I have the code below which is a part of a script that saves images onto my WordPress installation. The problem is that the script saves the image with the original name, for example "originalimage.jpg". What I want is that the saved image get's a random number assigned like, "randomnumber.jpg" and I wonder how I can do this so that it can take an already taken random number again if it already used one once. What I tried so far breaks the code. Can someone please help?
function wpr_save_all_images($content,$keyword,$insert) {
$path = wp_upload_dir();
$path = $path['baseurl'];
$html = $content;
if ( stripos( $html, '<img' ) !== false ) {
$regex = '#<\s*img [^\>]*src\s*=\s*(["\'])(.*?)\1#im';
preg_match_all( $regex, $html, $matches );
if ( is_array( $matches ) && ! empty( $matches ) ) {
$new = array();
$old = array();
require_once(ABSPATH . 'wp-admin/includes/file.php');
require_once(ABSPATH . 'wp-admin/includes/media.php');
require_once(ABSPATH . 'wp-admin/includes/image.php');
foreach( $matches[2] as $img ) {
if ( stripos( $img, "images/buynow-big.gif" ) !== false ) {
continue;
}
$size = getimagesize($img);
$width = $size[0];
$height = $size[1];
if ( $width < 2 || $height < 2 ) {
continue;
}
if ( stripos( $img, $path ) !== false ) {
continue;
}
$tmp = download_url( $img );
preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $img, $matches);
$newfn = str_replace(array("%2B", "%52", "%20", "%5"), "B", basename($matches[0]));
$oofnm = basename($matches[0]);
if($newfn != $oofnm) {
$newfn2 = str_replace(array(".jpg", ".png", ".gif"), "", $newfn);
$tmppath = pathinfo( $tmp ); // extract path parts
$newpth = $tmppath['dirname'] . "/". $newfn2 . "." . $tmppath['extension'];
rename($tmp, $newpth); // renames temp file on server
$tmp = $newpth;
}
$file_array['name'] = $newfn;
$file_array['tmp_name'] = $tmp;
// If error storing temporarily, unlink
if ( is_wp_error( $tmp ) ) {
@unlink($file_array['tmp_name']);
$file_array['tmp_name'] = '';
continue;
}
$id = media_handle_sideload( $file_array, $insert );
if ( ! is_wp_error( $id ) ) {
$url = wp_get_attachment_url( $id );
$thumb = wp_get_attachment_thumb_url( $id );
array_push( $new, $url );
array_push( $old, $img );
}
//echo "OLD: ". $img . "<br>WAWA: " . $wawawa . "<br>NEW: " . $url . " <br>";
}
if( !empty( $new ) ) {
$content = str_ireplace( $old, $new, $html );
$post_args = array( 'ID' => $insert, 'post_content' => $content, );
if (!empty($content))
$post_id = wp_update_post( $post_args );
}
}
}
return true;
}