I ran into a problem that I cannot understand.
During plugin development, I include the .js.php file (register / enqueue).
<? Header("content-type: application/javascript"); $path = constant('WP_PLUGIN_DIR'); //////////////////// 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 are working, but any WP CONSTANT will be unavailable.
This includes MY OWN constants that were declared in plugin.php (actually this is the reason I even started testing WP constants)
Interestingly, not only CONSTANTS are unavailable, but any wp function returns “unavailable”.
Permanent PHP should be available at all times through the application. Is this a specific WP issue? Is it intentional? or am i doing something wrong?
NOTE: I know there are other ways to do this (for example, use localize_script to pass variables to JS - or just use a function to output the path in the header), but first - these methods will not be ideal for me - and, more importantly, I want to understand why this method fails ...
EDIT I:
Altuh @ Matt Beckman pointed in the right direction that his specific method did not work. It is true that the WP file must be included. For me, 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: some of them Hardcoded (for example, @Salman A) suggested - what if changes in the plugin change? what is the solution in this case?
Please note that both wp-load.php
and wp-config.php
worked for me. I do not know which is better or might pose some security issues.
but I think this is for another question.
Bottom line: this solution is only TEMP until I find the correct answer. My plugin is loaded through the WORDPRESS plugin mechanism (enqueue_script () / register_script () / init (), etc.) - and therefore I cannot understand why it does this. Boo now works as described above.