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.

Read More

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.

Related posts

2 comments

  1. 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; ?>"; 
    
  2. 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");
    

Comments are closed.