Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wordpress > getting full path to my theme's images directory regardless of parent paths

Tags:

php

I have a function whose purpose is to list the folders within the images directory of my wordpress theme. It works great when the user has installed wordpress in the root directory of the site. However, it fails if the user has installed wordpress in a folder under the root...

$mydir = get_dirs($_SERVER['DOCUMENT_ROOT'].'/wp-content/themes/mytheme/images');

This function works fine as long as the wordpress is installed directly into the site's root, such as site.com/index.php

However, this path method fails, if the user has installed their blog in a virtual directory. Example: site.com/somedirectory/index.php

Can someone help with a better method of determining the path of the $mydir?

It would be super simple if I could feed my function with the http address, but my function requires the path to the images directory as a server directory. Anyone know of a way to find the folders under a given directory using the http method instead? For example, I can get a reference to my theme's images directory with...

$mydir = get_bloginfo('url').'/wp-content/themes/mytheme/images';

However, the function below, will not take a URL, it must be a physical file path to the chosen directory I want to parse. So I either need to replace it with a function that takes a URL or I need to find some way to convert the $mydir function to a physical path, or perhaps some other means.

Here is the function that I'm using for parsing the directory and assigning each folder to an array.

function get_dirs($path = '.') 
{
$dirs = array();
try
{
    foreach (new DirectoryIterator($path) as $file) 
    {
        if ($file->isDir() && !$file->isDot()) 
        {
        $dirs[] = $file->getFilename();
        }
    }
} 
catch(Exception $e) 
{
    //log exception or process silently
    //just for test
    echo "There is a problem inside the get_dirs function";
}
return $dirs;
}
like image 310
Scott B Avatar asked Dec 30 '25 07:12

Scott B


2 Answers

According to the codex the correct function to use is:

get_template_directory() 

Or if you want the uri:

get_template_directory_uri()
like image 55
spyderman4g63 Avatar answered Jan 02 '26 00:01

spyderman4g63


I prefer to use Wordpress functions when available. In this case that would be:

get_stylesheet_directory(). '/images';

This will return the images directory path in the currently selected theme, even if it's a child theme.

Function Reference/get stylesheet directory

like image 39
Christian Lescuyer Avatar answered Jan 01 '26 23:01

Christian Lescuyer