Friday, March 29, 2013

PHP/WordPress | Avoid hardcoded paths

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}  }


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

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

For generic use:

- Use existing functions to retrieve locations whenever possible, instead of hard coded or contants
- 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

- 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)

No comments:

Post a Comment