Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I wrote a simple function to get the contents in a folder (called templates) in my wordpress plugin, but am having problems getting the path to work (thus the function always dies). My question is: Is there a wordpress function or something that will give me the path to my plugin as required for the opendir function to work?

 function get_templates(){

    $path =   '[path to my plugin]/templates';

$dir_handle = @opendir($path) or die("Cannot open the damn file $path");

 while ($file = readdir($dir_handle)) {

  if(substr($file,-3) == "php" )

   continue;

  $TheLinkedFile = $path."/".$file;
 if(file_exists($TheLinkedFile)) {

echo $TheLinkedFile.'<br>';
 } else {
echo "nothing";
 }
 }

closedir($dir_handle);

  }
share|improve this question
add comment

2 Answers 2

Here is an example...

 //..path/to/wp-content/plugins/your-plugin-basedir/
 $path  = plugin_dir_path( __FILE__); 

 //..directory within your plugin 
 $path .= 'templates';                

 //..continue with your script...
 $dir_handle = @opendir($path) or die("Cannot open the damn file $path");

UPDATE

I tested the rest of your script by the way, to see if it in fact did read the directory and list files with the *.php extension and it wouldn't work.

Instead after modifying it to;

$dir_handle = @opendir($path) or die("Cannot open the damn file $path");

while ($file = readdir($dir_handle)) {

    //get length of filename inc. extension
    $length_of_filename = strlen($file); 

    //strip all but last three characters from file name to get extension
    $ext = substr($file, -3, $length_of_filename); 

    if($ext == "php" ) {

    $TheLinkedFile = $path."/".$file;

        if(file_exists($TheLinkedFile)) {
            echo $TheLinkedFile.'<br>';
        } else {
            echo "nothing";
        }
    }

}

closedir($dir_handle);

It works...

share|improve this answer
    
Great...that helps...thanks. –  Allen Sep 18 '12 at 1:26
add comment

I recently used the following code for batch processing some images but you can modify it to suit your needs:

<?php
$dir = plugin_dir_path( __FILE__ ) . 'path/to/files/';
foreach ( glob( $dir . '*.php' ) as $file ) {
    $file_name = basename( $file );
    // do what you want with  $file - no need to check for existence
}

Note: The purpose of my answer is to show an alternative way of doing this. An example use of this code can be found here on line 253.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.