TL;DR
$themes_search_index = strpos(__FILE__,\'wp-content/themes\');
$plugins_search_index = strpos(__FILE__,\'wp-content/plugins\');
$url_postfix_prospect = dirname(__FILE__);
if( $themes_search_index !== false ){
$url_postfix_index = strpos($url_postfix_prospect,\'wp-content/themes\');
} elseif( $plugins_search_index !== false ) {
$url_postfix_index = strpos($url_postfix_prospect,\'wp-content/plugins\');
}
$url_prefix = get_site_url();
$url_postfix = substr($url_postfix_prospect, $url_postfix_index);
$lib_path_url = $url_prefix .\'/\'. $url_postfix;
echo $lib_path_url;
Given the file path...
/var/www/html/example.com/wp-content/plugins/my-plugin/lib/an-awesome-library/autoload.php
Results to...
http://example.com/wp-content/plugins/my-plugin/lib/an-awesome-library
Problem
Building a plug-and-play library for wordpress that can either be "included" inside a theme or plugin can be difficult. Wordpress has no pre-defined function for getting the URL of that file.
Solution
Treat plugins and themes separately.
Step 1. Check whether included inside theme or plugin
/**
* Contains numeric values if the respective strings are found,
* Contains boolean `false` if the string is not found
*/
$themes_search_index = strpos(__FILE__,\'wp-content/themes\');
$plugins_search_index = strpos(__FILE__,\'wp-content/plugins\');
Step 2a. If inside a theme
$url_postfix_prospect = dirname(__FILE__);
$url_postfix_index = strpos($url_postfix_prospect,\'wp-content/themes\');
$url_prefix = get_site_url();
$url_postfix = substr($url_postfix_prospect, $url_postfix_index);
$lib_path_url = $url_prefix .\'/\'. $url_postfix;
echo $lib_path_url;
Step 2b. If inside a plugin
$url_postfix_prospect = dirname(__FILE__);
$url_postfix_index = strpos($url_postfix_prospect,\'wp-content/plugins\');
$url_prefix = get_site_url();
$url_postfix = substr($url_postfix_prospect, $url_postfix_index);
$lib_path_url = $url_prefix .\'/\'. $url_postfix;
echo $lib_path_url;