简体   繁体   中英

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.

You can just output javascript code from php like this:

<script>
var customamznsearch = "<?php echo addcslashes($customamznsearch, '"'); ?>";
</script>

Or if you mean to get it from the <meta> tags, then:

function getMeta(metaName) { 
   var metas = document.getElementsByTagName('meta'); 

   for (i=0; i<metas.length; i++) { 
      if (metas[i].getAttribute("name") == metaName) { 
         return metas[i].getAttribute("content"); 
      } 
   } 

    return "";
}

var twitterTitle = getMeta("twitter:title");

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; ?>"; 

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