You can use wp_localize_script to transfer data to Jacascript.
wp_register_script( ‘some_handle’, ‘path/to/myscript.js’ );
// Localize the script with new data
$data_array = array(
‘amzn_assoc_default_search_phrase’ => $php_variable
);
wp_localize_script( ‘some_handle’, ‘object_name’, $data_array );
// Enqueued script with localized data.
wp_enqueue_script( ‘some_handle’ );
https://codex.ww.wp.xz.cn/Function_Reference/wp_localize_script
Thanks for the reply.
However, the Javascript isn’t going to be a separate .js file – it’s just a small snippet on the embedded on the search.php itself. How would this alter the instructions?
use $_GET[‘s’] to get search query term.
Great, that makes sense. So, the javascript snippet is below. The key line is:
amzn_assoc_default_search_phrase = “searchterm”; //programmatically specify this
I need to take the results of the use $_GET[‘s’] command you mention and embed them into “searchterm”. How would I do this?
Thanks again.
—-
<script charset=”utf-8″ type=”text/javascript”>
amzn_assoc_ad_type = “smart”;
amzn_assoc_ad_mode = “search”;
amzn_assoc_marketplace = “amazon”;
amzn_assoc_region = “US”;
amzn_assoc_tracking_id = “mytag”;
amzn_assoc_default_search_phrase = “searchterm”; //programmatically specify this
</script>
<script src=”//z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US”></script>
It will be like
<script charset=”utf-8″ type=”text/javascript”>
amzn_assoc_ad_type = “smart”;
amzn_assoc_ad_mode = “search”;
amzn_assoc_marketplace = “amazon”;
amzn_assoc_region = “US”;
amzn_assoc_tracking_id = “mytag”;
amzn_assoc_default_search_phrase = <?php echo $_GET[‘s’]; ?> ; //programmatically specify this
</script>
<script src=”//z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US”></script>
Works very well – thanks so much, Deepak – I truly appreciate you assistance.
All the best
Terry
Never, EVER use user input in a PHP script without first sanitizing the input. The above code would allow someone to DDoS a site with a specially-crafted search term.
In this specific case, that means escaping all double-quote characters in the $_GET superglobal. Something like this:
amzn_assoc_default_search_phrase = "<?php echo str_replace('"', '\"', $_GET['s']); ?>";
Noted – thanks; I appreciate the warning. I updated the command and all looks great.
WordPress provide ‘sanitize_text_field’ function to sanitize the input data. It does more than removing the double quotes.
Behinds the scenes, the function does the following:
Checks for invalid UTF-8 (uses wp_check_invalid_utf8())
Converts single < characters to entity
Strips all tags
Remove line breaks, tabs and extra white space
Strip octets
In your code it will be like
$searchterm = sanitize_text_field($_GET[‘s’]);
amzn_assoc_default_search_phrase = <?php echo $searchterm ; ?> ; //programmatically specify this