I don’t use hardcoded URLS and paths in my code as most of my sites are for clients which have to be moved from the development server to the live server. In the database, it’s easy enough to modify the URLs through search & replace; but within files, it’s a recipe for disaster using a full URL or server path.
So as a cheatsheet for myself, I’ve documented all the ways we can write WP & Woo URLs and paths in PHP.
Difference URL and Path
A path is the server path to a file, which is used when we need to access the file from within the server eg to make sure it exists with is_file(); to check its last modification date with filemtime() or similar use. On my Linux cPanel server it looks like this: /home/username/public_html/filename.php
A URL is the address we use to access content such as a page, post, product or an image, PDF etc on the web. A typical URL would look like this: https://example.com
Paths & URLs
NB: These two URLs will often be identical but are not always! I’ve come across client sites where the displayed URL in the browser was modified and did not match the actual WP installation URL. So be careful which you use!
Further info: https://wordpress.stackexchange.com/questions/20294/whats-the-difference-between-home-url-and-site-url
get_home_url() retrieves the site’s home URL
get_site_url() retrieves the site’s URL where core files reside – this may not be the URL used to display the site to visitors! but this is the function to use when you need to reference file locations eg a PDF for download
get_stylesheet_directory() gives the Path to the current theme
get_stylesheet_directory_uri() gives the URL to the current theme. If a child theme is used, it gives the child theme URL.
get_template_directory_uri() gives the URL to the root theme. If a child theme is used, it gives the parent theme URL.
plugin_dir_path( __FILE__ ) gives the directory path to the the plugin file is currently in
plugin_dir_path( __DIR__ ) gives the parent directory path to the plugin file is currently in
plugin_dir_url( __FILE__ )
content_url() Retrieves the URL to the content directory in format https://example.com/wp-content (without trailing /)
url_to_postid() works the other way round!
wp_get_attachment_image_src() The returned array contains four values: the URL of the attachment image src, the width of the image file, the height of the image file, and a boolean representing whether the returned array describes an intermediate (generated) image size or the original, full-sized upload.
$order->get_view_order_url() The order object gives access to the order URL