I'd like a php link for my Wordpress attachments to appear in part of a javascript function, but my below attempt does not output any text:

var link = "<?php echo wp_get_attachment_link();?>";
function myFunction(link) {
    return link;

Is this an issue with formatting? Thanks!

  • 1
    PHP only runs on the server whereas JS runs client-side (in the browser). To execute any PHP functions, you will need an Ajax call back to the server.
    – jdm2112
    Commented Apr 18, 2017 at 19:21

1 Answer 1


To answer the question, no: It's not an issue with formatting, it's as jdm2112 explains the matter. You can, however, "send" the variable , or have it plucked from the server, either via an Ajax call as jdm2112 suggests or as set by wp_localize_script(). Which you use will likely depend on what the script does and when and how it's run.

  • 1
    If you want a global javascript variable, using wp_localize_script() is probably the best bet. If the variable is more dynamic, you'll want to use AJAX. You could start here: codex.wordpress.org/AJAX_in_Plugins
    – scott
    Commented Apr 18, 2017 at 20:22

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.