admin管理员组

文章数量:1323342

I need to display a script just after all my js files loaded via wp_enqueue_script

In my functions.php :

function list_hotels($hotels){ ?>
    <script>
        var positions = [];
        positions = <?php echo json_encode($hotels); ?>
    </script>
    <?php
}
add_action('wp_footer', 'list_hotels', 50, 1);

In my template (there is an available $hotels var which is an array) :

do_action( 'wp_footer', $hotels );

What's wrong with my code?

I need to display a script just after all my js files loaded via wp_enqueue_script

In my functions.php :

function list_hotels($hotels){ ?>
    <script>
        var positions = [];
        positions = <?php echo json_encode($hotels); ?>
    </script>
    <?php
}
add_action('wp_footer', 'list_hotels', 50, 1);

In my template (there is an available $hotels var which is an array) :

do_action( 'wp_footer', $hotels );

What's wrong with my code?

Share Improve this question asked May 7, 2018 at 10:07 William OdeWilliam Ode 1232 silver badges11 bronze badges 3
  • Try changing function list_hotels($hotels){ ?> to function list_hotels(){ global $hotels; ?> and you may also need to declare the $hotels as a global variable. E.g. global $hotels; $hotels = array( ... );. – Sally CJ Commented May 8, 2018 at 8:00
  • 1 @SallyCJ I hope you are joking when suggesting that anyone should use globals ;) – Mark Kaplun Commented May 9, 2018 at 14:01
  • Hehe.. but I'd actually provide a more appropriate answer if @WilliamOde replied... =) – Sally CJ Commented May 9, 2018 at 14:40
Add a comment  | 

2 Answers 2

Reset to default 3

The right way to pass extra parameters to hooks, in addition to the ones they declare is by using closures

in your case it will be something like

add_action( 'wp_footer', function () use ($hotels) { list_hotels($hotels) });

The use keyword enable sharing of variables between the context in which the closure is declared and the one it is being used (meaning, when the action is actually executed).

The best way of passing PHP variables to JavaScript is using wp_localize_script, which helps to localizes a registered script with data for a JavaScript variable.

Here is a solution in StackOverflow, from where you can get idea to fix your problem.

本文标签: How to pass argument to wpfooter hook with data from a template