0

How do I use a custom filed value in an external javascript? I'd like to use a custom field already stored for a post that is an url in an external javascript

<script type='text/javascript' src='http://www.my-website.com/wp-content/themes/mytheme/js/scripts.js'></script>

in order to open a new window

onclick="window.open('MY_CUSTOM_FIELD_VALUE');"

I tried to add

global $post; $cf = get_post_meta( $post->ID, 'my_custom_field', true );

but it doesn't work. Thanks for your help.

2
  • You might be able to do with Ajax. You have the control of the 'external JavaScript' ?
    – sri
    Commented Mar 24, 2014 at 10:17
  • yes I have control of the javascript... I've created it
    – advalue
    Commented Mar 24, 2014 at 10:36

1 Answer 1

0

I had a similar problem using custom field values in a widget that used JavaScript. I wrote a tutorial explaining it. Try this code:

<?php 
global $post;
$cf = get_post_meta($post->ID, 'my_custom_field', true);     
?>

<button onclick="window.open(<?php echo json_encode($cf); ?>);">Click me</button>
1
  • Thanks for your help. Do I have to insert your code in the js file? In my js I'd like to insert the function that I call in the <a href="openWindows()"... so I need to call the custom field directly from the js
    – advalue
    Commented Mar 27, 2014 at 17:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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