Search code examples
javascriptwordpressvariablesmeta

Assign Value of Custom Wordpress Post/Page Meta Field to JavaScript Variable


Is there a way via some lines of JavaScript to assign the value of a custom meta field in a Wordpress post/page to a JavaScript variable?

In other words, I've got a custom meta field in all my Wordpress posts and pages named "customamznsearch". I'd like to assign the value of that field to a JavaScript variable with the same name... or different name if need be.

Also, an added bonus would be to also define a static value for the variable if no data is available from that meta field.

This is the code that will be utilizing the "customamznsearch" variable.

<script type="text/javascript">
amzn_assoc_placement = "adunit0";
amzn_assoc_tracking_id = "livcouintheci-20";
amzn_assoc_ad_mode = "search";
amzn_assoc_ad_type = "smart";
amzn_assoc_marketplace = "amazon";
amzn_assoc_region = "US";
amzn_assoc_textlinks = "";
amzn_assoc_linkid = "0c1ce8995df23ae16ec99d3bb32502ec";
amzn_assoc_default_category = "SportingGoods";
amzn_assoc_default_search_phrase = customamznsearch;
</script>
<script src="//z-na.amazon-adsystem.com/widgets/onejs?MarketPlace=US"></script>

This code will be displayed in an Enhanced Text Widget in the footer of my page. The Enhanced Text widget should be fully capable of supporting Text, HTML, CSS, JavaScript, Flash, Shortcodes, and PHP.


Solution

  • After much research, the following snippet of code was what ended up working (please note that I decided to change the variable to 'amazonadserach'):

    var amazonadsearch = "<?php global $post;
    $amazonadsearch = get_post_meta($post->ID, 'amazonadsearch', true);
    echo $amazonadsearch; ?>";