• Resolved namchy

    (@namchy)


    It’s got me crazy! πŸ™‚ What is wrong with my piece of code? wp_localize_script doesn’t recognize my variable, even I declare it global in my function…
    Thanks!

    $phpvariable = "This is from PHP";
    
    function js_enqueue_scripts() {
        global $phpvariable; 
        wp_register_script( "hendlerskripte", "/mojaskriptax.js" );
        wp_enqueue_script( "hendlerskripte" );
        wp_localize_script( "hendlerskripte", "JS_object_php_var",  $phpvariable);
    }
    add_action( "wp_enqueue_scripts", "js_enqueue_scripts" );
Viewing 4 replies - 1 through 4 (of 4 total)
  • Moderator Steven Stern (sterndata)

    (@sterndata)

    Volunteer Forum Moderator

    It must also be declared as global outside the function.

    Thread Starter namchy

    (@namchy)

    Thank you for your reply.
    I thought this was a global variable outside my function, by definition

    A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function

    :

    $phpvariable = "This is from PHP"; // global scope

    …but obviously I’m wrong. πŸ™‚
    Please, a brief example how to do it would be great.

    • This reply was modified 5 years, 9 months ago by namchy.
    • This reply was modified 5 years, 9 months ago by namchy.
    Moderator Steven Stern (sterndata)

    (@sterndata)

    Volunteer Forum Moderator

    
    global  $phpvariable; 
    $phpvariable = "This is from PHP";
    
    function js_enqueue_scripts() {
        global $phpvariable; 
        wp_register_script( "hendlerskripte", "/mojaskriptax.js" );
        wp_enqueue_script( "hendlerskripte" );
        wp_localize_script( "hendlerskripte", "JS_object_php_var",  $phpvariable);
    }
    add_action( "wp_enqueue_scripts", "js_enqueue_scripts" );
    Thread Starter namchy

    (@namchy)

    Thank you dear sir, you saved my day!

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Global variable in wp_localize_script, help needed.’ is closed to new replies.