PHP/WordPress | Avoid hardcoded paths


Problem:
When writing themes and plugins, hardcoded paths such as "/wp-content/plugins" will not work on every environments, since these folders can change.

Here's a quick PowerShell script to look for those strings on file contents:
cd C:\Wordpress\wp-content\
$str = "wp-content"
gci -path . -include "*.php" -recurse | %{ $c = gc $_; if ($c -match $str){write-host $_.FullName}  }


Solution:

For themes:
- Use get_template_directory to retrieve the current theme's root folder
e.g. c:\wordpress\wp-content\themes\ThemeName

- use get_template_directory_uri to retrieve current the theme's root URL
e.g. http://wordpress.com/wp-content/themes/ThemeName

For plugins:
- Use dirname(plugin_basename(__FILE__)) to retrieve the current working folder (same as current file being edited)
e.g. c:\wordpress\wp-content\plugins\PluginName

- use plugins_url( '/css/style.css', __FILE__ ) to retrieve css/style.css URL under the current plugin working location
e.g. http://wordpress.com/wp-content/plugins/PluginName/css/style.css


For generic use:

- Use existing functions to retrieve locations whenever possible, instead of hard coded or contants
get_admin_url()
get_home_url()
get_site_url()
- Use dirname(__FILE__) to retrieve the folder of the current file being edited (__DIR__ is recent and not supported by PHP versions prior to 5.3.0)
- Use __FILE__ or __DIR__ contants to retrieve current file or directory paths


Notes:
- Always check if the current function is adding the trailing slash to avoid having two (url//file.extension)
- Avoid using hardcoded paths ('/wp-content/plugins') or constants (WP_CONTENT_URL, WP_PLUGIN_URL)

Comments

Popular posts from this blog

Breaking down document locking in SharePoint

Working around X-Frame-Options for iframes

Document ID not being generated