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?

  • How are you including this js?
    – GavinR
    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>
    – Sean Lee
    Aug 16, 2011 at 4:29
  • Why you don't want to use wp_localize_script?
    – Mamaduka
    Aug 27, 2011 at 19:36
  • I need external js, not inline. Wp_localize_script is for inline
    – Sean Lee
    Aug 28, 2011 at 21:17
  • 2
    wp_localize_script is for external, enqueued js, not inline.
    – Milo
    Nov 6, 2011 at 1:34

1 Answer 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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.