最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp localize script - Using wp_localize_scripts

programmeradmin4浏览0评论

I'm trying to work out how to send a PHP variable from a page template to an AJAX function (which in turn pulls data via a function in functions.php using admin-ajax.php). I understand I'm meant to use wp_localize_script, but can't get it to work in either my page template or functions.php.

In functions.php:

add_action( 'wp_enqueue_scripts', 'enqueue_theme_scripts' );
function enqueue_theme_scripts() {  
    wp_register_script('xxx', get_stylesheet_directory_uri() . '/assets/js/xxx.js', array ( 'jquery' ), null, true);
    wp_enqueue_script('xxx');
    wp_localize_script( 'xxx', 'yyy', array( 'ajax_url' => admin_url( 'admin-ajax.php'), 'a_value'=> '10' ) );
    wp_localize_script( 'xxx', 'zzz', 'hello' );
}

So I'm trying to retrieve 'hello' as a variable in xxx.js. My understanding is that with the code above I should be able to do:

alert(zzz);

But it doesn't work. What am I doing wrong?

And how does it work if I want to grab a PHP variable from my page template php file, not from functions.php? I can't find any online examples...

发布评论

评论列表(0)

  1. 暂无评论