Menü schliessen
Created: March 5th 2024
Last updated: March 16th 2024
Categories: Common Web Development,  Php,  Wordpress
Author: Tim Fürer

WordPress: How to get URL of theme file relative from current file

Tags:  function,  guide,  PHP,  wordpress
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Are you a WordPress developer looking for a more efficient way to handle theme file URLs in your code? If so, you might find our helper function, relative_resource_uri(), quite useful. This function is designed to simplify the process of generating URLs for theme resources relative to the current file, making your coding tasks a bit easier.


Helper Function

<?php

function relative_resource_uri($path, $resource = '') {
    $path = trailingslashit(dirname($path));

    $base = untrailingslashit(substr($path, strlen(trailingslashit(get_stylesheet_directory()))));

    return trailingslashit(get_stylesheet_directory_uri()) . "{$base}/{$resource}";
}

?>

How it works

This function takes two parameters:

  • $path: The path to the current file.
  • $resource: The path to the desired resource within the theme directory.

Here's what happens under the hood:

  • dirname($path): Retrieves the directory name of the current file's path.
  • trailingslashit(): Ensures the directory path ends with a trailing slash for consistency.
  • get_stylesheet_directory(): Returns the absolute path to the current theme's directory.
  • substr(): Extracts the portion of the directory path relative to the theme directory.
  • untrailingslashit(): Removes any trailing slashes from the extracted base path.
  • get_stylesheet_directory_uri(): Retrieves the URL of the current theme's directory.
  • Concatenates the theme directory URL with the relative resource path to form the complete URL.

Usage

<?php

echo relative_resource_uri(__FILE__, 'path/to/other/file');

?>

In this example:

  • __FILE__ represents the path of the current file.
  • 'path/to/other/file' is the relative path to the desired resource from the current file within the theme directory.