What is the correct way to convert the absolute path of the executing script to a URL, in WordPress?

wordpress.stackexchange https://wordpress.stackexchange.com/questions/80270

  •  04-11-2019
  •  | 
  •  

Question

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?

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top