WordPress Code Snippets

A fresh mix of code snippets and tutorials

Getting Path Info with PHP and WordPress

291

Massive round-up of PHP and WordPress techniques for getting various directory and file path information. This is a mega-reference aimed at PHP/WordPress developers.

Note: these snippets are designed for straight-up copy/pasting into any PHP or plugin script. The results should be well-formatted and easy to read.

PHP: Get file paths

Working with or without WordPress, and assuming we are including the following snippets in a plugin directory named /simple-ajax-chat/ (this is just an example; you can include these snippets in any PHP script located in any directory):

These snippets are entirely PHP, so they work in any directory, with or without WordPress. Note however that basename(dirname(__FILE__)) returns the current directory name, so if your script is in a subdirectory, you can get the parent directory name by adding another dirname(), like so: basename(dirname(dirname(__FILE__))).

WP: Get plugin paths

Working with WordPress, and assuming we are including the following snippets in a plugin directory named /simple-ajax-chat/ (this is just an example, you can include these snippets in any WordPress plugin):

Note: to get the path for the plugin in which the script is included, use plugin_dir_path(). But if you need to get the path of a some other plugin, you can use WP_PLUGIN_DIR.

WP: Get plugin URLs

Working with WordPress, and assuming we are including the following snippets in a plugin directory named /simple-ajax-chat/ (this is just an example, you can include these snippets in any WordPress plugin):

Example: Combining these different techniques, here is a way to get the current plugin URL from a script that is included in a subdirectory, say, /simple-ajax-chat/inc/myscript.php

echo plugins_url(basename(dirname(dirname(__FILE__)))) .'/css/sac.css';

..which outputs:

http://example.com/wp-content/plugins/simple-ajax-chat/css/sac.css

Again, the best way to see how these snippets work is to copy/paste them into your WordPress plugin or PHP script (depending on the snippet), and then check the results.

Also check out this useful post at the WP Codex.

WP-Mix File-Path Trilogy

Learn more

WordPress Themes In Depth


Show Support

Like our new Facebook Page to show support!