Relative path instead of absolute for wp_enqueue_script

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?

3 Answers
3

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

<?php
//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.
}

Leave a Comment