简体   繁体   中英

Is it possible to change a JS String Variable in script.js file from a WordPress template PHP file?

I have a issue that I want to solve but do not fully understand on how to approach it and wondering if anybody on here knows a way at all.

In my WordPress theme I have a script.js file located in a JS Folder which has a script for loading an Instagram feed on page load.

$(window).on('load', function(){
 $.instagramFeed({
'username': 'usernamehere',
'container': "#instagram-feed-demo",
'display_profile': false,
'display_biography': false,
'display_igtv': false,
'items': 9,
'items_per_row': 3,
  'styling': false
 });
}); 

In my WordPress single page template I want to populate the username string by using a custom field but if I move the script into the template in a script tag it does not work but works fine in the script.js file.

Does anybody know a way to populate the string from the single template at all?

Not sure if I understand correctly what you need but you might check the template where it loads the script.js file (using a wp_enqueue_script function) and add another call to wp_localize_script function using the same handler name and pass it an array of variables to be available for the javascript.

Example:

wp_enqueue_script('script-handler', 'url to the script.js file', []);
wp_localize_script('script-handler', 'jsObjectName', [
  'username' => $usernamehere,
]);

The js object jsObjectName created with the wp_localize_script function will precede the call for the script.js file, making it's values available for use in the script.

Now change the Instegram code to something like this:

$(window).on('load', function(){
  $.instagramFeed({
    'username': jsObjectName.username,
    'container': "#instagram-feed-demo",
    'display_profile': false,
    'display_biography': false,
    'display_igtv': false,
    'items': 9,
    'items_per_row': 3,
    'styling': false
  });

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM