Support

Account

Home Forums Front-end Issues How to get ACF text field inside queued jQuery file

Solving

How to get ACF text field inside queued jQuery file

  • Hi all!

    I am looking to get an ACF field that is on a CPT inside some custom jQuery. This jQuery is in a file that is already being queued via functions.php. It’s a text field that I need to display on a page that is not the CPT, so that’s why the post_id is in there. What i have currently is showing up as commented out (not sure by what though).

    var endResult = "<?php echo the_field('end_result', $post_id); ?>" ;
    
    jQuery("a.btn-alert.btn-tag-closed").before("<span class=\"end-result\"> " + endResult + " </span>");

    ends up as <!--?php echo the_field('end_result', $post_id); ?--> when viewed in browser inspect. Also the same endResult without the echo does the same thing.

    How can I get the ACF field end_result inside of jQuery?

    Thanks!
    Ben

  • You can’t put PHP inside a JS file unless the JS file itself is parsed as PHP, which it isn’t. The easiest way would probably be to add the JS with PHP inline to the document header, possibly using the wp_head action hook (I’m not very experienced with action hooks, that’s just what I would assume is approrpiate).

  • I would, if it’s possible use wp_localize_script() https://developer.wordpress.org/reference/functions/wp_localize_script/ to insert the data I needed into the page.

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘How to get ACF text field inside queued jQuery file’ is closed to new replies.