0

I am building a WordPress site for the first time for a client. I deployed Apache and MySQL locally and installed WordPress by hand. All of the links from page to page are using the absolute URL locally (e.g. localhost:8080/index.php/a-page).

When I move to deploy this site, am I going to have to update every single link by hand? If so, is there a way to develop the site such that the links are relative to the base URL?

1

WordPress generate urls dynamically, using the data from the database. It is up to themes/plugins to use wordpress functionalities to generate urls instead of hardcoding them.

Wordpress has a series of functions that are supposed to be used when dealing with urls, some of them are:

  • get_template_directory_url (theme url)
  • plugin_dir_url (plugin url)
  • get_stylesheet_directory_url (stylesheet url)

For example, when you place an <a href="">Menu Item</a> in a theme template, the href attribute of the anchor shoudn't have a hardcoded url like localhost:8080/link-to/the-post, instead, you should use get_post_permalink() (if we are dealing with a post), that returns the relative url for the post.

If you have to use the url to an image that's located in my-theme/assets/img/my-img.png, you would compose the image src using get_template_directory_url, instead of hardcoding the url to the theme forlder:

<img src="<?php echo get_template_directory_url(); ?>/assets/img/my-img.png"/>

The same goes to files paths. Hardcoded paths will fail if the site moves from server. Wordpress provides functions like

  • get_template_directory (theme path)
  • plugin_dir_path (plugin path)
  • get_stylesheet_directory (stylesheet path)

Some urls might end up hardcoded in the database. It usually happens with urls in posts contents and posts metadata.

The easiest way to replace urls in the database is to use a plugin. When I have to, I use the Better Search Replace plugin. It lets you search and replace the url in the wordpress tables.

search replace

You search for your old url, and replace with the new one. Selecting every table, and replacing GUIDs (you can read about what are GUIDs and when to replace them here)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.