changing the url of all images with my cdn pull zone url

i want to use a cdn url to all images only on my multisite installation. is there any way to do it without any plugin? i just want to change the url of all images network wide. since i have a pull zone cdn url available.

  • Ash
    • WordPress Hacker

    Hello Ian Andrew Macalisang

    Would you please try the code below:

    add_filter('wp_get_attachment_image_src', 'staticize_attachment_src', null, 4);
    function staticize_attachment_src($image, $attachment_id, $size, $icon)
    {
    	if (is_array($image) && !empty($image[0])) {
    		$image[0] = str_replace( 'START OF ORIGINAL URL TO UPLOAD FOLDER', 'CDN URL TO UPLOAD FOLDER', $image[0] );
    	}
    	return $image;
    }

    You need to set the correct URL for your site and CDN.

    The URLs stored in the database, you can use the_content hook to alter them or use a search and replace plugin in the database: https://wordpress.org/plugins/search-and-replace/

    If the URLs are hardcoded, then there is no way to replace them using other codes, neither with any plugin as well.

    Have a nice day!

    Cheers,
    Ash

  • andyware012
    • Flash Drive

    Hi Ash,
    btw, im using a multisite network so i want all subsites and mapped domain to be using the same cdn url on all images. is there a way on how to do this just like hummingbird wpmu cdn is handling js and css assets via wpmucdn?

    and can you tell which file i should insert the snippet above?

  • Ash
    • WordPress Hacker

    Hello Ian Andrew Macalisang

    For any custom php code, you can use that code in your child theme's functions.php if the theme is not changed. Otherwise mu-plugin is the best option. To create a mu-plugin, go to wp-content/mu-plugins folder. If there is no mu-plugins folder then, create one. Now, inside the mu-plugins folder create file with name anything.php (make sure file extension is .php). Now start with a <?php tag and then put the above code.

    About your original issue, you need to know how the files are uploaded in the CDN. Do they maintain exactly same folder structure as wordpress uploads folder? If so, then the above code should work :slight_smile:

    Have a nice day!

    Cheers,
    Ash

Thank NAME, for their help.

Let NAME know exactly why they deserved these points.

Gift a custom amount of points.