PHP
wp_enqueue_scripts 是本地化数据的好时机。确保以脚本为目标,为对象创建名称,并传递数据数组。在这种情况下
twitter_settings
将创建并保存所有数据的对象。
twitter_settings.tweets_widget_id
将最终保持
$tweet
.
add_action( \'wp_enqueue_scripts\', function() {
// Get the current data
if ( empty ( $tweet = get_theme_mod( \'tweets_widget_id\' ) ) ) {
$tweet = \'No Widget ID\';
}
// Localize script with data to `twitter_settings` object
wp_localize_script( \'twitter\', \'twitter_settings\', array( \'tweets_widget_id\' => $tweet ) );
// Enqueued script with localized data.
wp_enqueue_script( \'twitter\' );
} );
访问
twitter_settings
对象
var config2 = {
id: "" + twitter_settings.tweets_widget_id, // based on comments
domId: "tw-widget2",
maxTweets: 3,
enableLinks: !0,
showUser: !1,
showTime: !0,
showInteraction: !1,
lang: "en"
};
twitterFetcher.fetch(config2);
测试(可选)测试以确保变量通过ok。
<script>
(function ($) {
alert( twitter_settings.tweets_widget_id );
})(jQuery);
</script>