Deploying Local WordPress Site

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="https://wordpress.stackexchange.com/questions/354661/<?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)

tech