Error in using glob function with wordpress

Asked

Viewed 179 times

2

I am trying to recover images from a folder with native php function glob, only one is returning array emptiness.
I’m passing the full path from folder to function.

Follows code:

$pasta = get_template_directory_uri() . '/img/projetos/' . get_post_meta($post->ID, 'projeto', true) .'/';              
$imagens = glob("$pasta{*jpg,*png}", GLOB_BRACE) or die ("Erro ao acessar $pasta");
  • Please report the error that is happening.

  • What is the value of the concatenation "$folder{*jpg,*png}"? Can you print and post here? This notation you are trying to use I only know in shell, in regex I would do something like (jpg|png).

2 answers

2

You are passing a URL (get_template_directory_uri) but the glob is waiting for a Path/Path (get_template_directory).

The following code works:

$pasta = get_template_directory() . '/img/' ;              
$imagens = glob("$pasta{*jpg,*png}", GLOB_BRACE) or die ("Erro ao acessar $pasta");
echo '<pre>' . print_r( $imagens, true ) . '</pre>';

And to convert the Path to URL, it would be a simple:

$path = get_template_directory();
$url = get_template_directory_uri();
foreach( $imagens as $img )
    echo str_replace( $path, $url, $img ) . '<br />';

0

First of all, make sure your $folder path is valid "need to end with /"

Then use this:

$a = glob($pasta.'*.{jpg,png}',GLOB_BRACE);
echo '<pre>';
print_r($a);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.