In a nutshell, my question is “How do I convert the absolute path of the executing script, e.g.,
/home/content/xx/xxxxxxxx/html/wp-content/plugins/MY_PLUGIN_DIR/MY_PLUGIN/MY_PLUGIN.PHP
or
/home/content/xx/xxxxxxxx/html/wp-content/themes/MY_THEME/functions.php
to the absolute URL?”
http://example.com/wp-content/plugins/MY_PLUGIN_DIR/MY_PLUGIN.PHP
or
http://example.com/wp-content/themes/MY_THEME/functions.php
I don’t even need the actual script name, just the path up to directory it’s in.
Background
I’ve created a class that greatly simplifies creating an option page for a plugin. It doesn’t (yet) do the heavy-lifting of registering/adding options via the Settings API, it’s more a helper class that
- creates the menu item (add_menu_page or add_submenu_page)
- creates a plugin action link in the plugins listing page (plugin.php)
- displays a custom icon in the menu (if a top-level menu item)
- injects stylesheets and/or javascript files in the head – the WP way (register/enqueue)
- a few other misc. things related to creating an option page
It does these things with a minimal number of options passed in the instantiation of the class.
Problem
I created this class with only plugins in mind, but realized it works out of the box for themes, too…except in regards to generating URLs from relative references. Right now, I use
$my_url = plugins_url('/', __FILE__)
to generate URLs for stylesheets, script files (.js), and the menu icon file that are associated with the option page only if the user enters a relative URL. If they enter an absolute URL, I don’t touch it. Example: if you include 'icon_url' => 'images/my-icon.png'
as an option, the class would convert that to
http://example.com/wp-content/plugins/MY_PLUGIN_DIR/MY_PLUGIN/images/my-icon.png
But since I’ve decided to make this class work for themes as well, I’ve realized I can’t use plugins_url
. I’m trying to stay away (if possible) from forcing the user to specify whether this class is going to be used for a plugin or a theme.
Is there a WordPress way similar to plugins_url()
that I could use?
Call get_stylesheet_directory_uri() for the current theme, or get_template_directory_uri() for the parent theme of a child theme, and append your file paths to that.
Edit: To determine whether you’re in a plugin, a parent theme or a child theme, compare the folder you’re in (via
dirname(__FILE__)
) to plugin_dir_path(), get_template_directory() and get_stylesheet_directory() respectively.In your
wp-config.php
file, at the very end it should defineABSPATH
to be the wp root folder. You can then replace that from your filepath withsite_url
(or, if you’ve instead checked the path for theme/plugin/upload directory, then the appropriate url-function listed at https://codex.wordpress.org/Function_Reference/plugin_dir_url#Related)