I've just completed my first Wordpress site for a client and sent the files via FTP transfer to their server. I've just received the following comment back -
"...a few things don’t seem to be displaying properly, or linking correctly… It looks as though they’ve used absolute links instead of relative ones, so certain things aren’t pulling through properly..."
I didn't even realise this would be an issue as I assumed all the links would require changing anyway. Is there a code function that can go in the functions.php
file to amend this? I've seen that there is a wp_make_link_relative
and the following filters -
add_filter( 'post_link', 'wp_make_link_relative' ); // Normal post link
add_filter( 'post_type_link', 'wp_make_link_relative' ); // Custom post type link
add_filter( 'page_link', 'wp_make_link_relative' ); // Page link
add_filter( 'attachment_link', 'wp_make_link_relative' ); // Attachment link
add_filter( 'get_shortlink', 'wp_make_link_relative' ); // Shortlink
Should I apply these to my functions.php file? Will that fix everything or do I need to apply anything else, like a plugin?
To achieve relative links for your images/icons, JS and CSS assets do the following.
I suppose you've your assets layed out like this,
- theme-name
- - assets
- - - images
- - - css
- - - js
So, to access a file named scripts.js
in your js
directory, use the following code to link to it
get_stylesheet_directory_uri() . '/assets/js/scripts.js'
It'll return the following URL
http://example.com/wp-content/themes/theme-name/assets/js/scripts.js
I don't know if it's the best solution, but it works.
Add this constant in index.php
define( 'WP_CONTENT_URL', '/wp-content');
Topic about this solution is there: Relative URLs in WordPress
There are several places where URLs get defined. The above lines should work for most of them, but not media or any custom API work. Also, WordPress SEO plugins like Yoast create absolute URLs, which can negatively impact your SEO if you edit them in the database.
If they say "things don't seem to be displaying properly..." they may mean assets. For that, go to
Settings > Media > Full URL path to files and change it to /wp-content/uploads.
For absolute URLs in JS files, in functions.php create a function like this:
function create_root_url() {
wp_localize_script( '<your-main-js-bundle>', 'any-variable-name', array(
'root_url' => get_site_url()
));
}
add_action( 'wp_enqueue_scripts', 'create_root_url' );
Then in your JS file, change your hard-coded url to:
const endpoint = `${any-variable-name.root_url}/wp-json/api...`;
or whatever your purpose may be.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With