php - Plugin/theme relative PATH/URI

I would like to get relative path from a php file without knowing the absolute path. I have succeeded to do it but for a reason which I don't know, on some servers (in rare case) it doesn't work when I enqueue css/js. Slashes are missing...

Here the code:

define('PATH', trailingslashit(str_replace('\\', '/', dirname(__FILE__))));
define('URI', site_url(str_replace(trailingslashit(str_replace('\\', '/',ABSPATH)), '', PATH)))

What did I miss? Does it come from the server or the code itself?

Topic plugins-url paths php Wordpress

Category Web


function get_url_from_path ($path) {

    // clean paths
    $dir_path = str_replace( '\\', '/', $path ) ); // file or directory
    $site_dir = trailingslashit( str_replace( '\\', '/', ABSPATH ) ); // path set in wp-config

    // remove server directory from path
    $file_rel = str_replace( $site_dir, '', $dir_path );

    // convert relative url to absolute url
    $dir_rel_url = site_url ($file_rel, 'http' );

    // return
    return $dir_rel_url;    
}

// __FILE__ and __DIR__ are referencing the php calling these functions

echo get_url_from_path (__FILE__);

echo trailingslashit( get_url_from_path (__DIR__) );

Just don't do it, you can never know if the plugins directory is even "below" ABSPATH, and you can not know the URL out of the directory path https://codex.wordpress.org/Determining_Plugin_and_Content_Directories.

Just use the core api of plugins_utl etc, don't reinvent the wheel.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.