0

I have a JS/PHP file combined in file.js.php in a wordpress plugin.

The problem is - that I need to include a wordpress file in order to be able to use the GLOBALS and wp functions .

My question has 2 parts :

1 - which file is the best one to include (security, performance etc..)

2 - how can I find he path to said file - presuming I can not use plugins_url() befor including it to identify the path or wp root ?

For now I am using :

include("../../../../wp-load.php");

or

require_once (dirname(dirname(dirname(dirname(dirname ( __FILE__))))).'/wp-config.php');

But of course it is a semi-hard coded method . It will not guarantee nothing if the CONTENT" or "PLUGINS" dir was moved ...

The problem was outlined and surfaced while resolving this question : PHP constant inside JS file

Community
  • 1
  • 1
Obmerk Kronen
  • 15,619
  • 16
  • 66
  • 105

1 Answers1

0

I think what you're doing is too complicated. I think a better method would be to checkout how AJAX calls in WordPress are handled: http://codex.wordpress.org/AJAX_in_Plugins

You don't actually have to write the JS as AJAX to use these methods, but you can place some settings variables into your pages using these methods. You can also have a javascript file that is generated fully by WordPress meaning that it has full access to the database etc.

so you can write your code around

add_action( 'wp_ajax_nopriv_myajax-submit', 'mydynamicjs' );
add_action( 'wp_ajax_myajax-submit', 'mydynamicjs' );

and make calls from inside or outside wordpress to include that JS like:

http://example.com/wordpress/wp-admin/admin-ajax.php?action=mydynamicjs

not really proper technique as you should actually be returning JSON however you will get a file that has 100% access to WP functions, database etc without having to do any crazy includes.

You could also just write something to access the data you need over AJAX depending on your goals with this.

nullvariable
  • 537
  • 3
  • 12