0

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

myscript.php

<?php header('Content-Type', 'text/javascript');
?>
  jQuery(document).ready(function(){

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

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

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

          });        
    }


jQuery('select').each(function(index) {
            jQuery(this).chosen({
                disable_search_threshold: 1
            });
        })

    });

in functions.php:

add_action('wp_enqueue_scripts','wordpress_scripts');
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);
    wp_enqueue_script('myscript');
}

Any suggestions to make this work?

3
  • 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? 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 Commented Jun 2, 2014 at 16:58

1 Answer 1

1

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

functions.php

$var=get_current_user_id();

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

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

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.