Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

On my site I have some posts with a custom field "Name". Now, in case the post has "Name" set, I want to generate this code:

<script type='text/javascript'>
    var FG_DONATE_BUTTON_PARAMS = { attribution: 'honor',   attribution_name: Name}     
</script>

where Name after attribution_name refers to the custom field value. For test purpose, I've used this code in the header

$nameAttribute= get_post_meta($post->ID, 'Name', true); 
printf('<script type=\'text/javascript\'>
var FG_DONATE_BUTTON_PARAMS = { 
    attribution: \'honor\', 
    attribution_name: \'' . $nameAttribute .'\'
} </script>');

But I have two problems. One, the value of the $nameAttribute doesn't get passed through, and secondly, it's ugly :) I think I can manage the value problem, but I'm unsure what would be the "proper" way to output this.

share|improve this question
3  
Don't print <script> into the page, use wp_enqueue_script and wp_localize_script instead. As shown explained: ottopress.com/2010/… –  OleVik Jan 13 '12 at 21:23
add comment

1 Answer

up vote 1 down vote accepted

You may wish to look at this question. In that question, the admin-ajax url is passed through, but it can be any variable (or array of variables), like for instance $nameAttribute.

For instance, you would call

wp_localize_script('my_js_file_handle','my_js_object',array('attribute'=>$nameAttribute))` 

then in your js file, the variable would be accessible from my_js_object.attribute.

(You must enqueue the javascript file though!)

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.