When you enqueue scripts or styles with the following:

function themeslug_enqueue_style() {
    wp_enqueue_style( 'core', '/style.css', false ); 
add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_style' );

You get the following:

<link rel='stylesheet' id='core-css'  href='http://localhost:8080/wordpress/style.css?ver=4.9.4' type='text/css' media='all' />

Note that it appends the site url to the beginning, in this case http://localhost:8080. I'm trying to remove this so that it's relative to the file executing this. Usually this is done with plugins_url or get_stylesheet_uri(). However, I DO NOT want to use either of these, as it may be used as a plugin or included in the theme - and I want to keep the code the same for both.

Is there a way to do this?


Not with the Wordpress API, but you can do it with vanilla PHP pretty easily.

//Get the full path of the local directory first.
$fullpath = __DIR__;

//check if you are in a theme directory or a plugin directory
if (strpos( $fullpath, 'themes' ) !== false )
    //It's a theme, use get_stylesheet_uri

} elseif ( strpos( $fullpath, 'plugins' )
    //It's a plugin, use plugins_url

} else {
    //It's somewhere else entirely.
| improve this answer | |
  • Thanks @mopsyd but how would this remove the site url from wp_enqueue_script? – Troy Templeman Mar 23 '18 at 15:42
  • It doesn't. It uses the correct prefix depending whether you are a theme or a plugin. The underlying functionality of the *_enqueue_* functions is pretty opinionated, and it makes a bunch of decisions about your source that you have no control over. So to get it to work you have to give it a valid full url, or else it is going to automatically decide that your source is supposed to be relative to your script or plugin whether you like it or not. – mopsyd Mar 23 '18 at 20:44
  • So the solution there is not to bypass the *_enqueue_* stuff, particularly if you ever want anything using it to be allowed on the wordpress.org repo (they will reject it if it bypasses enqueue), but to have a smart switch that knows which one applies when, so you have a more portable template that you can reuse. – mopsyd Mar 23 '18 at 20:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.