PHP
wp_enqueue_scripts is a good time to localize the data. Make sure you target your script and create a name for the object as well as passing an array of data. In this case twitter_settings
is the object that will be created and will hold all the data. twitter_settings.tweets_widget_id
will ultimately hold your $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' );
} );
JS
Access the localized data from the twitter_settings
object
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);
Test
(optional) Test to make sure the variable came through ok.
<script>
(function ($) {
alert( twitter_settings.tweets_widget_id );
})(jQuery);
</script>