2

How to write an external javascript file with dynamic variable values generated using php from wp db values?

So instead of using wp_localize_script for inline js variables, I'd like to use wp_enqueue_script with $src pointing to this php file acting like external js.

So far, on the external js using php, the content as follow:

Header("content-type: application/x-javascript");
$params = array(
  'timezone_string'           => get_option( 'timezone_string' ),
  'jump_to_top'           => __( 'Jump to top' ),
  .....
);
echo "$timezone_string $jump_to_top;
.....

When viewing page source, the external script file is listed correctly, but clicking on the external file link, it takes me to home page. I added wp-load.php, still the same.

How to do this correctly?

6
  • How are you including this js? Commented Aug 16, 2011 at 2:21
  • using wp_enqueue_script, the written format will appear as just as this: <script type='text/javascript' src='http:/domain.com/js/js.php'></script> Commented Aug 16, 2011 at 4:29
  • Why you don't want to use wp_localize_script? Commented Aug 27, 2011 at 19:36
  • I need external js, not inline. Wp_localize_script is for inline Commented Aug 28, 2011 at 21:17
  • 2
    wp_localize_script is for external, enqueued js, not inline. Commented Nov 6, 2011 at 1:34

1 Answer 1

1

Rather than generating whole script dynamically it would make more sense (from logical and caching perspective) to use static script that will fetch data required via generic Ajax request to WP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.