what is the correct way of using relative paths in wordpress theme development?

10,045

A simple solution, (not necessarily the most proper way) if you're needing the path within the theme index file could be something like so:

 <?php
        $TEMPLATE_PATH = get_template_directory_uri(); 
        $TEMPLATE_PATH = parse_url($TEMPLATE_PATH, PHP_URL_PATH);
      ?>

You'd then be able to use the $TEMPLATE_PATH as a relative path like so:

<link href="<?php echo $TEMPLATE_PATH; ?>/favicon.ico" rel="shortcut icon" type="image/x-icon"/>

this would be output like the following:

<link href="/wp-content/themes/ThemesName/favicon.ico" rel="shortcut icon" type="image/x-icon"/>

Hope someone finds this useful.

Share:
10,045

Related videos on Youtube

GKman
Author by

GKman

Updated on July 10, 2022

Comments

  • GKman
    GKman almost 2 years

    I am writing a some code for wordpress theme development that I plan on reusing for future themes (maybe even uploading to github). it consist of a few dozen files and some javascript and css files as well.

    the only commitment I am willing to make for the future is that all my files will be placed in the same directory, where will this directory be placed inside the theme directory is unknown.

    how should I go about enqueuing files (wp_enqueue_style, wp_enqueue_script functions) if I don't know the files absolute path (get_template_directory_uri . '')?

    also I hope that instead of having a dozen lines of include\require, I can write one include file that will include the rest of the files by their relative paths.

  • GKman
    GKman about 7 years
    your answer assumes that my files are always in 'mytheme/reusable', directory, but it can also be 'mytheme/inc' or something else. I want it dynamic. I tested successfully having all my files in one directory along with a loader.php file similar to this: include ('file1.php'); //relative to loader.php include ('file2.php'); then in the function.php: include (get_template_directory() . 'dynamic-path/loader.php'); so I don't rely on constant paths. As I said it worked with php files but I work out the enqueue part of it. also I don't know if it will work in the future or cause problems