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 |2 Answers
Reset to default 3The 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
版权声明:本文标题:How to pass argument to wp_footer hook with data from a template 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742132485a2422225.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
function list_hotels($hotels){ ?>
tofunction 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