Wordpress: Serve images from a CDN - wordpress

I use a CDN to serve my images, which I upload into Wordpress. My settings were:
It worked perfectly but it doesn't work anymore since I updated to Wordpress 4.5. This are my settings now:
This filter doesn't work either:
function my_cdn_upload_url() {
return 'http://media.mydomain.com';
}
add_filter( 'pre_option_upload_url_path', 'my_cdn_upload_url' );
Does anyone know how should I serve my images from a CDN?
Thank you.

Looks like you upgraded from quite an old WP version, didn't you? Uploads folder and path options were removed in Settings -> Media a long time ago.
So what does your real path for uploads look like? It's not a standard domain.com/wp-content/uploads// correct?
If yes - where do new images get uploaded to after the upgrade?
Try playing around with https://wordpress.org/plugins/custom-upload-dir/ and see if it helps get your images back to CDN.

The easiest way is editing the content of "upload_url_path" in the wp_options table:
upload_url_path > http://media.mydomain.com
Thank you!

The problem with the approaches above are you won't have file write permissions to upload images to your CDN.
Another approach is to upload all of your images to somewhere - e.g. Amazon S3, or keep them on affiliate network CDNs - and then store your image URLs in postmeta for your posts or products.
You then need to alter your theme files to pull the images from the postmeta fields instead of from the featured image or thumbnail fields.
FYI - this approach will massively speed up imports since WordPress will create multiple sizes of images using up CPU and disk space.
I created a plugin to solve this:
https://www.wpintense.com/product/external-images/

There is a hidden admin page where you can find all the options:
http://localhost/wp-admin/options.php
Find the upload_url_path option and set a value.
Note:
After you give it value, then the "Store uploads in this folder" which is the upload_path, and "Full URL path to files" which is the upload_url_path options will also appear on the Media Settings page:
http://localhost/wp-admin/options-media.php
The options only appear on the Media Settings page if a value is already set. This is the code in WordPress Core that defines how it works:
/*
* If upload_url_path is not the default (empty),
* or upload_path is not the default ('wp-content/uploads' or empty),
* they can be edited, otherwise they're locked.
*/
if ( get_option( 'upload_url_path' ) || get_option( 'upload_path' ) && 'wp-content/uploads' !== get_option( 'upload_path' ) ) :

BEST WAY is to use w3 total cache.
It has a built in cdn support and of course you can use it's main functionality , caching , most useful to speedup website.

Related

What is the way to upload bulk images in wordpress?

I have more than 500 images and I want to upload in WordPress media, I tried through FTP, WordPress changed images in different dimensions, and when I installed plugin "ADD TO SERVER " it uploads all the files.
I just want to add original images in the WordPress dashboard. Is there any way to upload bulk files in the WordPress media?
You can do it through FTP but go to settings before and change to import ORIGINAL size instead change dimensions.
You can find it under SETTINGS --> Media.
I have use 1024/1024 as max to avoid overload the server. You can change it on 2K(2048) or 4K(4096).
You can use the intermediate_image_sizes_advanced hook to prevent WordPress from getting the list of image sizes it normally uses.
The following code will feed an empty array to WordPress instead of the registered list of image sizes:
add_filter( 'intermediate_image_sizes_advanced', function(){
return [];
}, 10, 2 );
Running the Add to server plugin again after adding that code to your functions.php should not resize your uploaded images.

Change ouput url of WordPress [Gallery] Shortcode

I recently installed ta plugin that now uploads my images from the media library to s3.
I have also FTP's the entire uploads folder to s3 which encompasses about 4000 images.
I have used throughout my site the wordpress gallery shortcode however somewhere and somehow it outputs the siteurl.
How do I change this so that I can override the url to be the one from my S3 bucket?
I will admit I have no idea what I am doing here or where to start and I really will appreciate your help :)
You can filter images src attribute output and replace old url with new url as follow. copy below code to your theme functions.php and replace www.oldurl.com and www.newurl.com with your own urls.
add_filter('wp_get_attachment_image_src', function ($image) {
if(is_array($image)){
$image[0] = str_replace('www.oldurl.com', 'www.newurl.com', $image[0]);
}
return $image;
}, 999);
Looking into the wp_get_upload_dir(), that's a wrapper for wp_upload_dir(), that's again wrapper for _wp_upload_dir(), we see that the upload url can be modified through the upload_url_path option.
Since you're moving all of your uploads to S3, you could try to add your S3 bucket base url into the upload_url_path option.
You should test this first on your dev install, just to see how it works with your current setup.
You might want to make a search & replace via the database.
You can see here how to make a SQL Query to change the Image Path in the posts: 13 Useful WordPress Queries
UPDATE wp_posts SET post_content = REPLACE (post_content, 'src="http://www.oldsiteurl.com', 'src="http://yourcdn.newsiteurl.com');
UPDATE wp_posts SET guid = REPLACE (guid, 'http://www.oldsiteurl.com', 'http://yourcdn.newsiteurl.com') WHERE post_type = 'attachment';

How can I successfully use browser-sync with wordpress locally?

I'm trying to get browser-sync to work with my multipress wordpress install, for simpler mobile / responsive development.
Currently I'm having problems in that, my normal development takes place at local.example.com, and browser-sync is proxying this (via 123.456.78.9:3202, as per browser sync).
So far browser-sync loads the site, but none of my scripts or CSS are loading (although images load fine). They jsut fail with no response in the network panel.
I'm using NGINX for hosting the site, as opposed to apache.
Does anyone have any wordpress browser-sync experience? Am I missing something with the browser-sync set up? And tips for this would be super welcome. I'd love to get this as a solid part of my work flow.
The problem is to do with how wordpress handles URLs, in that it normally uses full URLs for including content and links etc.
The proxy is trying to access these on another domain and that's why it's failing.
Update
A much simple, cleaner and maintainable strategy, that also helps with development environments is to use the Root Relative URLs plugin. Adds hooks and configs similar to below, but also updates your content and editors to apply the same structure, so it's a bit more robust
Original Answer
You can add a simple hook (source: wordpress relative urls) to filter wordpress generated urls and remove the base domain so you get relative links to styles and posts etc:
$relative_url_filters = array(
'script_loader_src', //js
'style_loader_src', //css
'post_link', // Normal post link
'post_type_link', // Custom post type link
'page_link', // Page link
'attachment_link', // Attachment link
'get_shortlink', // Shortlink
'post_type_archive_link', // Post type archive link
'get_pagenum_link', // Paginated link
'get_comments_pagenum_link', // Paginated comment link
'term_link', // Term link, including category, tag
'search_link', // Search link
'day_link', // Date archive link
'month_link',
'year_link'
);
foreach ( $relative_url_filters as $relative_url_filters ) {
add_filter( $relative_url_filters, 'wp_make_link_relative' );
}
Which should clean up most of your issues and get browser-sync working nicely.
I'm still having some issues where I have more complex inclusions for images, but more or less it's working and we're already seeing how cool it is!

How to customize Wordpress Theme before going live

Yesterday I installed a new theme on Wordpress on my self-hosted website. I am aware of the feature that allows you to preview a theme and have used it to select a new Theme that I want to install.
Problem
I do not want to interrupt normal operations of my website, but this new theme requires a lot of customization before it is ready to go. How do I do this?
My Crappy Solution
Is the only way to go about it to run a virtual server on my desktop? This seems tedious, not to mention all the errors I usually get when switching to the "real" server when doing this.
A better way?
I've been searching on SO as well as the WordPress Forum for an answer as to how to do this, but have come up short. I would have thought this is a common question. Maybe I'm using the wrong search terms [themes, customization, before installing]???
Any help is greatly appreciated! Thanks!
Ok, since your question is a pretty good one and probably not a few people are going through the same process when they decide to update their site, I decided to give a try to the get_stylesheet and get_template filter hooks. It turns out that with a very small plugin, you can easily enforce a specific theme(well in this case any logged-in visitor, but you can change this to use any logic you want) according to a specific rule/s.
Here's the code that you need to put in a file in your plugins directory:
<?php
/*
Plugin Name: Switch Theme
Description: Switches the theme for logged-in visitors, while keeping the current theme for everyone else. !!!NOTE!!! Please back-up your database prior using this plugin - I can't guarantee that it will work with any theme, nor that it won't break your site's set-up - USE AT YOUR OWN RISK(I did a quick test and it seemed to be fine, but haven't done extensive testing).
You don't need to switch to the desired theme before that - you want to keep active the theme that you will display to your visitors - the one that you will see will be used programatically.
Before activating the plugin, change the line that says `private $admin_theme = '';` to `private $admin_theme = 'theme-directory-name';` where "theme-directory-name" is obviously the name of the directory in which the desired theme resides in.
*/
class MyThemeSwitcher {
private $admin_theme = '';
function MyThemeSwitcher() {
add_filter( 'stylesheet', array( &$this, 'get_stylesheet' ) );
add_filter( 'template', array( &$this, 'get_template' ) );
}
function get_stylesheet($stylesheet = '') {
if ( is_user_logged_in() && $this->admin_theme ) {
return $this->admin_theme;
}
return $stylesheet;
}
function get_template( $template ) {
if ( is_user_logged_in() && $this->admin_theme ) {
return $this->admin_theme;
}
return $template;
}
}
$theme_switcher = new MyThemeSwitcher();
So - first of all BACKUP YOUR DATABASE! I tested locally with Twenty Eleven being the default theme and a basic framework theme as my custom theme - the theme options and navigation menus were saved properly.
Then all you need to do is to update the file(change the line that says private $admin_theme = ''; to private $admin_theme = 'theme-slug'; where theme-slug is the name of the directory in which the theme you want to use is).
Also - you won't be able to change the Front page and Posts page options, without this affecting the live site, nor will you be able to change the any shared components that both themes use(Site name, Front Page, Posts page, Posts Per Page, etc options, content and so on).
So if you have no clue whether this solution is for you - well, it depends.
If both themes are not relatively complex, then most-likely you should be able to use this hack. If they are though maybe you should do a second installation of your website as others suggested - I think that a second installation in either a sub-domain or a sub-directory would be the best option for you(simply because moving a multisite database is more complex than moving a normal WP database).
I'd setup local apache server with a wordpress installed to customize and test a new theme. When you finished customizing it then you can upload the theme to your live site and activate it. If there are settings that you need to set in the dashboard then you probably will have to adjust them again. That's one way to test/customize a theme before putting it live.
You could create a network (make WordPress multisite with define('WP_ALLOW_MULTISITE', true);, see : http://codex.wordpress.org/Create_A_Network) and then create one sub-site, then turn it "off" with a Maintenance plugin so it is not accessible to users not logged in as admin, export your posts & data from main blog, import them in sub-blog with WordPress default importer, then apply your new theme to this sub-blog and work on it. When everything satisfies you, apply the theme to the main site and deactivate subsite.

Wordpress 3 Multisite with same Medialibrary

i created a Worpress 3 Multisite with 5 Sub-Blogs.
Is it possible to share the same Media-Library in this Blogs?
i changed upload_path in wp_1_options and wp_2_options for example and also in my backend in "Super Admins" Menu but it has no effect.
The files are uploaded to wp_contents/blogs.dir/1-2-3/files and the options have no effect.
any ideas? thanks!
One way around is to hook onto the load events of all media admin files, and switch to the main blog using switch_to_blog(1).
This would mean in any blog admin, the media library will always run as if it were on the main blog.
Note that a couple caveats include;
The media library for all blogs is stored in the main blog database table.
You may run into problems with inserting media into posts outside the main blog admin
You will run into problems with inserting galleries into posts outside the main blog admin
User permissions may be false positives or negatives
My best advice would be to use the code example below, and have a good play around with blog admins, logged in as different users, with different roles, and see what happens.
function use_main_blog_library()
{
switch_to_blog(1);
}
add_action('load-media-new.php', 'use_main_blog_library');
add_action('load-media-upload.php', 'use_main_blog_library');
add_action('load-media.php', 'use_main_blog_library');
add_action('load-upload.php', 'use_main_blog_library');
In my searching on this topic, several posts lead back to this one, so I figured I'd share an idea that might help someone wanting to develop a suitable plugin to solve this...
Use get_site_option() and update_site_option() to store global plugin options.
Add an option via hooks to choose if a media upload should be shared network-wide and let the plugin track which media files and where they're located at.
Again, using hooks, have the shared items show up in each blog's media library and perhaps add an indicator showing the file is a network share.
I have spent several hours playing with the administrator hooks and filters and this could be accomplished through them, although I'm not savvy enough to know how to fully integrate it with all of the media library features.
The Shiba Media Library Plugin could serve as a valuable reference since they have utilized several custom features for the Media Library via hooks and filters.
I really wish I had the spare time to work on this right now because I would take my best shot at it. I hope this helps someone else.
I have found a possible solution, which works for me in WP3.7.1 (I haven't tested it in earlier versions)
Create a filter, which overrides the default upload directories:
add_filter('upload_dir', 'ms_global_upload_dir');
function ms_global_upload_dir($uploads)
{
$ms_dir = '/sites/' . get_current_blog_id();
$uploads['path'] = str_replace($ms_dir, "", $uploads['path']);
$uploads['url'] = str_replace($ms_dir, "", $uploads['url']);
$uploads['basedir'] = str_replace($ms_dir, "", $uploads['basedir']);
$uploads['baseurl'] = str_replace($ms_dir, "", $uploads['baseurl']);
return $uploads;
}
Important: the 'Upload Url Path' settings should be empty in Site Settings or if you need to customize it, check the results by dumping the $uploads array to view possible conflicts.
To check if your version of WP supports this method, locate function wp_upload_dir() in file wp-includes/functions.php and find function call: $uploads = apply_filters( 'upload_dir' ...
If it presents, the solution above should work.
Hope, this helps ...
Additionally, I have spent almost two days to make a solution to replicate/delete the uploaded media in each of the blogs with action hooks 'add_attachment' and 'delete_attachment' by generating the necessary post and postmeta entries in the corresponding database tables. With this, you can add/delete media in any of the blogs, that will be visible in/removed from all blogs media library. If you are interested, I can share it...
Cheers

Resources