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?

  • Why don't you enqueue your scripts conditionally? Commented Jun 2, 2014 at 16:33
  • Because of too many conditions. I guess wp_localize_script might be an idea?
    – yumba
    Commented Jun 2, 2014 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
    Commented Jun 2, 2014 at 16:58

1 Answer 1


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.

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.