Home › Forums › General Issues › acf not defined – JavaScript API
I’m trying to use the ACF JS API, however when I try to inspect the acf object in the console, the console returns
(Uncaught ReferenceError: acf is not defined
I’m using the latest Version of ACF, 5.8.0 beta 3 and have jQuery installed too. Am I missing a step in order to be able to use the acf JS API?
Your script is running before ACF is initialized. More than likely you’re including your script too soon or running it too soon. When are your enqueuing your script? You should probably do this on the acf/input/admin_enqueue_scripts
hook https://www.advancedcustomfields.com/resources/acf-input-admin_enqueue_scripts/
Something not mentioned, but an added precaution is to make your script dependent of “acf-input”
Also ensure that your script does not run until the document is ready.
John, thanks for your reply. Does that mean I should create a separat JS file in order to use the acf js api and shouldn’t use my main.js file with the hook add_action( 'wp_enqueue_scripts', 'my_scripts' );
?
And can you explain what you mean by making the script dependant on ‘acf-input’? I don’t quite understand.
Sorry I did not get back to this sooner.
When I build custom JS that extends ACF I use a separate JS file for this. I enqueue this script when ACF does so that it’s only loaded when ACF is.
// this is lacking, but I want to highlight how to make your script dependent acf
add_action('acf/input/admin_enqueue_scripts', 'my_acf_extension_enqueue');
function my_acf_extension_enqueue() {
$handle = 'my-handle';
$src = 'url of script';
// $deps is where we tell WP what scripts need to load first
// https://developer.wordpress.org/reference/functions/wp_enqueue_script/
$deps = array('acf-input');
wp_enqueue_script($handle, $src, $deps, false, true);
}
The topic ‘acf not defined – JavaScript API’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.