I am using _s theme .I have all js files under js folder.My code

function _s_scripts() {
$js_dir = get_template_directory_uri() . "/js/";
foreach(glob($js_dir.'/*.*') as $file) {
$label = str_replace(".", "", $file);
wp_enqueue_script($label, $js_dir . $file . '.js', array('jquery'), '1.0.0');
add_action( 'wp_enqueue_scripts', '_s_scripts' );

Upon inspecting I found no jquery files loaded.PS I want to use glob function.

  • Any progress on that question? Please do follow up on answers to your questions. – kaiser Mar 15 '15 at 13:35

i think you're putting too many extra bits on the file and path strings.

try this :

function _s_scripts() {
$js_dir = get_template_directory_uri() . "/js/";
foreach(glob($js_dir.'*.*') as $file) {
$label = str_replace(".", "", $file);
wp_enqueue_script($label, $file , array('jquery'), '1.0.0');
add_action( 'wp_enqueue_scripts', '_s_scripts' );

when I run a similar function locally against a dir, the extra "/" and extra ".js" you were adding can causing files to not be found. Also - you added the $js_dir a second time, when $file will already have that information associated to it


to better explain : $file already had ".js" in its name, when you appended a second ".js" - those files logically do not exist (unless you have naming conventions that were not mentioned.

Also - in $js_dir - you already have the trailing forward slash, but when you try to search for /*.* - thats not a valid pattern so it further confuses glob.

this is at least how I understand it. A test harness I wrote was :

ini_set('error_reporting', E_ALL);
$js_dir = "/Users/MYUSER/Sites/";
$fileglob = glob($js_dir.'*.*');
echo count($fileglob);
foreach( $fileglob as $file) {
    $label = str_replace(".", "", $file);
    echo $file; 
    echo "done";

One more Edit:

To make this a better search, instead of *.* do this : ....

foreach(glob($js_dir.'*.js') as $file) {

that way, if you have other, system files (like thumbnail icons, text files, etc.. ) they don't get gathered up with the glob

  • and for reference - this is general php and not a wordpress specific issue. made some edits to the answer to be more complete. – Brandt Solovij Dec 11 '14 at 16:37

Ancient thread.

Helpful above, but get_template_directory_uri() won't work because glob needs a path name, not a URI (url).

We need get_template_directory().

$js_files = get_template_directory() . '/ng/';
foreach(glob($js_files.'*.js') as $file) {
  $labelarray = explode("/", $file);
  $label = str_replace(".", "", substr(array_pop($labelarray), 0, -3));
  wp_enqueue_script($label + '-js', $file , array('jquery'), '1.0.0');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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