4

On a wordpress environment.

I'm trying to automatically add versioning to my scripts using filemtime, but get the following error message:

Warning: filemtime() [function.filemtime]: stat failed for (file name)

the code is simple

$myfile = get_template_directory_uri() . '/js/script.js';
wp_enqueue_script('mywebsite-script',$myfile , array( 'jquery' ), filemtime( $myfile ), true );

the path to the file is correct, but as I said I get the stat failed message.

If I add the if (file_exists($myfile)) check, the whole operation is skipped. Yet if I echo the path to $myfile, this is correctly printed and can be opened in the browser!

The path does not contain fancy characters. The server is not on Windows, I've read encoding might be a reason for this but don't know what the workaround should be, if that's the case.

Where's could the problem be?

nonhocapito
  • 466
  • 5
  • 18
  • file permissions ... that's my thought, does php have permission to the file. – ArtisticPhoenix Dec 21 '16 at 08:17
  • @ArtisticPhoenix: yet php can read the file, enqueue the script via Wordpress... shouldn't it be able to read the file time just as well? Do you know if there is a way to check if it is a permission problem via php? – nonhocapito Dec 21 '16 at 08:22

1 Answers1

12

You should use the real path instead:

$myfile = get_template_directory_uri() . '/js/script.js';
$realpath = get_template_directory().'/js/script.js';
wp_enqueue_script('mywebsite-script',$myfile , array( 'jquery' ), filemtime( $realpath ), true );
christian Nguyen
  • 1,530
  • 13
  • 11
  • I thought this had failed too, but I was wrong, I had messed up while commenting out parts. This worked. Thanks! Funny how I found examples out there using the `_uri` Wordpress thingy. – nonhocapito Dec 21 '16 at 08:42
  • I just found out that this breaks locally on my xampp. The "real path" to the script now looks something like: `http://localhost/folderD:foldersonhardiskwithnospaces/wp-content/themes/theme/js/script.js`... – nonhocapito Dec 21 '16 at 14:06
  • get_template_directory() will return a real path such as: /var/www/wordpress/wp.local/wp-content/themes/twentyseventeen (linux) I see you provide is an 'uri' not 'directory path'. am I wrong ? – christian Nguyen Dec 21 '16 at 16:03
  • 1
    yes, I needed it for `filemtime` but not for `wp_enqueue_script`. Now I've separated the two, as I described [here](http://stackoverflow.com/questions/41265585/strange-behavior-of-wp-enqueue-script-on-a-local-xampp-install), answering my own question. – nonhocapito Dec 21 '16 at 16:12