WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'm trying to use PHP variables inside a javascript function. What's a proper way to use a WP function like get_current_user_id() inside a script that get's enqueued via wp_enqueue_script? Right now I get this error

Error:Call to undefined function...


<?php header('Content-Type', 'text/javascript');

         jQuery("#location option").each(function () {
             if (jQuery.inArray(jQuery(this).val(), locs) != -1) {
                 jQuery(this).prop('selected', true);

         if ( typeof jQuery.fn.chosen !== 'undefined' ){

            if($userID=='3') { 
         } else {
         jQuery("#location").chosen({ max_selected_options: "<?php echo $max; ?>"


jQuery('select').each(function(index) {
                disable_search_threshold: 1


in functions.php:

function wordpress_scripts() {
    wp_register_script( 'chosen', get_template_directory_uri() . '/assets/libraries/chosen/chosen.jquery.min.js', array( 'jquery' ),'',true);
    wp_enqueue_script( 'chosen' );

    wp_register_script('myscript', get_template_directory_uri().'/assets/js/myscript.php', array('jquery'),'',true);

Any suggestions to make this work?

share|improve this question
Why don't you enqueue your scripts conditionally? – Pieter Goosen Jun 2 '14 at 16:33
Because of too many conditions. I guess wp_localize_script might be an idea? – SPi Jun 2 '14 at 16:38
What are those conditions? You shouldn't be trying to use WordPress APIs outside of WordPress using standard standalone PHP files – Tom J Nowell Jun 2 '14 at 16:58

I found out about wp_localize_scripts here and it solves my issue:



$params = array(
  'max' => $var

wp_localize_script( 'myscript', 'MyScriptParams', $params );

and in the .js file I can retrieve this variable with MyScriptParams.max.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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