根据提供的代码,您似乎误解了wp_localize_script 作品函数的签名如下所示:
wp_localize_script( $handle, $name, $data );
哪里
$handle 是已注册或排队的JavaScript文件的名称
before 使命感
wp_localize_script. 看看
example in the codex (我在下面添加了行号):
1: <?php
2:
3: // Register the script
4: wp_register_script( \'some_handle\', \'path/to/myscript.js\' );
5:
6: // Localize the script with new data
7: $translation_array = array(
8: \'some_string\' => __( \'Some string to translate\', \'plugin-domain\' ),
9: \'a_value\' => \'10\'
10: );
11: wp_localize_script( \'some_handle\', \'object_name\', $translation_array );
12:
13: // Enqueued script with localized data.
14: wp_enqueue_script( \'some_handle\' );
看看上面的第4行。首先,将JavaScript文件注册到
$handle \'some_handle\'.
接下来,在第11行,wp_localize_script() 用于注册脚本句柄的本地化数据\'some_handle\' 在第4行注册。
最后,在第14行,JavaScript文件(在第4行注册)被排队。因为wp_localize_script() 同样通过了$handle WordPress在第4行注册,自动在每个wp_enqueue_script( \'some_handle\' ); 被调用。
换句话说,您需要使用wp_localize_script with 已注册的JavaScript文件。而不是像你现在所做的那样。
此报价来自the notes section 或多或少地说了同样的话:
IMPORTANT! 必须在使用wp\\u register\\u script()或wp\\u enqueue\\u script()注册脚本后调用wp\\u localize\\u script()。
还有,我认为你不需要json_encode() 你的$data. WordPress应该为您做到这一点。