Short Version
I need to give in the absolute path of a Javascript file that is to be hooked into something. It works if I hardcode it into
‘http://mywebsite.com/folder/script.js’
However I prefer not to hardcode it in. I can do dirname(___FILE___)
, which gives me this:
‘/home/public_html/folder/script.js’
But that fails, the script isn’t loaded. What’s the best practice to find the absolute path (starting with ‘http://’)?
–
Long Version
On this page in the WordPress documentation relating to the tinyMCE plugin creation, I found this:
// Load the TinyMCE plugin : editor_plugin.js (wp2.5)
function add_myplugin_tinymce_plugin($plugin_array) {
$plugin_array['myplugin'] = URLPATH.'tinymce/editor_plugin.js';
return $plugin_array;
}
There’s a note at the bottom saying:
Note: when using the mce_external_plugins filter, the url should point
to the actual plugin file, as in the example above.
A bit higher in the documentation they say
mce_external_plugins: passes in/out an associative php array
‘plugin_name’ => ‘plugin_url’. The url should be absolute and on the
same domain as your WordPress installation.
I am completely puzzled because I can’t find any information about ‘URLPATH’ which is used in their example. I don’t think it exists in PHP, WP or TinyMCE, but I could be wrong.
Incidentally, were this to be an error in the WP documentation, what would I replace URLPATH with to make it work?
Assuming your resource is included in your Plugin:
plugins_url()
is the URL towp-contentplugins
(Codex ref)So if you have a .js file in
wp-contentpluginsplugin-slugfile.js
:<?php echo plugins_url() . 'plugin-slugfile.js'; ?>
BUT WAIT!!
If your purpose is actually to load a javascript file, you actually want to enqueue that file, using
wp_enqueue_script()
, hooked into thewp_enqueue_scripts
hook.And
wp_enqueue_script()
uses the filepath rather than the URL, so you could usedirname(___FILE___)
if that’ what you’re comfortable with.