Support

Account

Home Forums General Issues Use the_field in a JavaScript file

Unread

Use the_field in a JavaScript file

  • Hi,

    I’m enqueue’ing scripts based on WordPress page template, and I need those scripts to be able to echo out ACF values. For example, my script files dynamically build up HTML which includes custom fields e.g.:

    innerHTML = <img src="<?php echo the_field('ad_banner'); ?>"

    Is it possible to echo these fields in a .js file, to build up those HTML strings?

    Thanks very much,
    Rob

    EDIT – I’ve now managed to resolve this.
    In case anyone else comes up against the same issue, the answer was to use wp_localize_script like this:

    wp_localize_script('pagination-retailers', 'script_vars', array(
            'banner' => get_field("ad_banner"),
    	'banner_link' => get_field("banner_link")
            )
        );

    Then call it in JS like this:
    script_vars.banner
    etc.

Viewing 1 post (of 1 total)

The topic ‘Use the_field in a JavaScript file’ is closed to new replies.