skip to Main Content

I’ am trying to get a list of file names from a directory folder and append them to an existing select dropdown filed as options.

add_action ('wp_head', 'testf');

function testf() {
    
$customer = md5( WC()->session->get_customer_id());
echo "<script>console.log('Debug Objects: " . $customer . "' );</script>";
    
$dir = '/wp-content/uploads/wapf/655dd0b1b2276/'.$customer.'';
echo "<script>console.log('CFilePath: " . $dir . "' );</script>";
    
$files = glob($dir . "*.png,jpg,jpeg,tif ");
foreach($files as $file)
{
echo "<script language= 'JavaScript'>alert(' . $file . ');</script>";}
$('select[class="user-file-uploads[]"]').append("<option value='" +$file+ "'>" +$file+ "</option>");

}

What is working is both $customer and $dir – console log screenshot below.

enter image description here

We added an alert for testing purposes as in this case their is only one file that matches the file extension types declared in the glob – the file being a .png.

No alert is showing, and similarly the select dropdown field does not display the expected option. As you can see we are trying to select the select input field by class name.

What am I doing wrong?

All help appreciated

2

Answers


  1. A couple of problem are:

    Your path is not correct you need to separate it with a slash:

    $dir = '/wp-content/uploads/wapf/655dd0b1b2276/' . $customer . '/';
    

    You also need to update your pattern like this in order to match any of the extensions:

    $files = glob($dir . "*.{png,jpg,jpeg,tif}", GLOB_BRACE);
    

    From the manual:

    GLOB_BRACE – Expands {a,b,c} to match ‘a’, ‘b’, or ‘c’

    Login or Signup to reply.
  2. I hope this updated code helps that fixes your code which has the glob pattern without the braces {}, also the javaScript code should be wrapped in a jQuery(document).ready block to ensure it runs after the DOM is fully loaded.

    add_action('wp_head', 'testf');
    
    function testf() {
        $customer = md5(WC()->session->get_customer_id());
        echo "<script>console.log('Debug Objects: " . $customer . "');</script>";
        
        $dir = '/wp-content/uploads/wapf/655dd0b1b2276/' . $customer;
        echo "<script>console.log('CFilePath: " . $dir . "');</script>";
    
    
        $files = glob($_SERVER['DOCUMENT_ROOT'] . $dir . "/*.{png,jpg,jpeg,tif}", GLOB_BRACE);
    
        echo "<script language='JavaScript'>";
        echo "jQuery(document).ready(function($) {";
    
        foreach($files as $file) {
            $filename = basename($file); 
            $url = $dir . '/' . $filename; file
            echo "$('select[class="user-file-uploads[]"]').append('<option value="" . esc_js($url) . "">" . esc_js($filename) . "</option>');";
        }
    
        echo "});";
        echo "</script>";
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search