WordPress has the built-in plugins_url() function. According to its documentation, the first parameter
$path is optional and provides a method to append a string to the returned default value of the function. So, given the example below the return value would be
At this point we would expect the result to point to our plugin’s actual root directory. What though if you accidentally entered the wrong value? A wrong value can create unwanted programming errors or bugs which will require investigation to correct.
An Alternative Approach
plugins_url() is great and does exactly what it is designed to do. But what if you could avoid the potential issue of fat fingering its first parameter value? To do this, let’s take advantage of another WordPress built-in function named plugin_basename().
This function also accepts a parameter but this time it is required. Truth be told you can fat finger this too. But this time you can avoid the issue by using the PHP Magic Contant
__FILE__. Also, we’ll use PHP’s explode() function to create an array of strings delimited by the forward slash (“/”). This time we get an output similar to
echo explode( '/', plugin_basename( __FILE__ ) );
Note: If you are Microsoft Windows backslashes (“\) are used instead. WordPress handles this situation for you automatically by using wp_normalize_path().
At this point can probably see how things are about to come together. All that is needed now is to join the two results together as shown below.
|* Create an array of strings based upon this plugin's root directory directory (not web root). Each index|
|* of the array is delimited by the file system path for this file. This file may, or may not be, located in|
|* a subdirectory of a plugin's source files.|
|$this_file_relative_path = explode( '/', plugin_basename( __FILE__ ) );|
|$this_plugin_directory_url = plugins_url( $this_file_relative_path[ 0 ] );|
Using this approach you avoid the potential for errors by eliminating the use of manual entries for parameters.