I am facing a problem that I can not understand .
During a plugin development I am including a file.js.php (register/enqueue).
<?
/*
File.js.php
*/
Header("content-type: application/javascript");
$path = constant('WP_PLUGIN_DIR'); //test with function
$path_2 = WP_PLUGIN_DIR; // test directly
//can cause a problem with older browsers?? use text/javascript
?>
//////////////////// Begin Tests ////////////
var templateDir = "<?php echo WP_PLUGIN_URL ?>" ;
var templateDir2 = "<?php echo $path ?>" ;
var templateDir3 = "<?php echo $path_2 ?>" ;
var templateDir4 = "<?php echo constant("WP_PLUGIN_URL") ?>";
var templateDir5 = "<?php echo __FILE__ ?>";
var templateDir6 = "<?php echo plugins_url( 'somedir/somefile.png' , dirname(__FILE__)) ?>";
Results :
var templateDir = "WP_PLUGIN_URL" ; // simply outputs a string of the constant name
var templateDir2 = "" ; // null or empty
var templateDir3 = "WP_PLUGIN_DIR" ;// simply outputs a string of the constant name
var templateDir4 = "//Warning: constant() Couldn't find constant WP_PLUGIN_URL in .."
var templateDir5 = "path.to.js.php" // only one that works ;
var templateDir6 = "Call to undefined function plugins_url() in.. "
so my tests showed me that MAGIC CONSTANTS work , but any WP CONSTANT will be unavailable .
That includes MY OWN constants that were declared in the plugin.php (actually this is the reason why I even began testing the WP constants )
Interesting enough - not only CONSTANTS are unavailable - but any wp function is returning "unavailable" .
PHP constant are meant to be available at all times through the app.. Is that a WP specific problem ? Is that intentional ? or am I doing something wrong ?
NOTE : I know there are other ways to do it (like using localize_script to pass variables to JS - or just use a function to output the path in the header) - but first - those methods will not be ideal for me - and more importantly is the fact that I want to understand why this method is failing ...
EDIT I :
Althouh @Matt Beckman pointed in the right direction his specific method did not work. It is true that a file from WP must be included . For me both the following work :
include("../../../../wp-load.php");
require_once (dirname(dirname(dirname(dirname(dirname ( __FILE__))))).'/wp-load.php');
Both as you can imagine are equal - but the problem remains : those are somewhat Hardcoded (like @Salman A) suggested - what if the plugin´s dir changes ?? what is the solution in that case ?
Note that the both wp-load.php
and wp-config.php
worked for me . I do not know what is better or which can present some security issues.
but I guess it is for another question ..
Bottom line : this solution is only TEMP until I will find the right answer . My plugin is loading via the WORDPRESS plugin mechanisem (enqueue_script() / register_script() / init() etc.. ) - and therefor I can not grasp why it does so.. Bu for now it works like described above.