Wordpress > getting full path to my theme's images directory regardless of parent paths
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 dir开发者_StackOverflowectory. 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;
}
According to the codex the correct function to use is:
get_template_directory()
Or if you want the uri:
get_template_directory_uri()
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
I don't have Wordpress installed here, but what if you put this in your functions.php located in your theme folder?
function get_dir_path(){
return dirname(__FILE__).'/images';
}
Then, instead of
$mydir = get_bloginfo('url').'/wp-content/themes/mytheme/images';
you just do
$mydir = get_dir_path();
FILE is an useful "magical" constant.
Might be what you're looking for: Template Tags/bloginfo « WordPress Codex
Instead of $_SERVER['DOCUMENT_ROOT']
you could use home_url.
For example, home_url( '/' ) . 'wp-content/themes/mytheme/images'
will generate a link http://localhost/
followed by the rest of the url.
精彩评论