Support

Account

Home Forums Bug Reports Javascript API returning NULL

Solved

Javascript API returning NULL

  • I’m enqueuing my script like this.

     // Sitewide.js
      wp_enqueue_script('KPX-JS', get_stylesheet_directory_uri() . '/js/sitewide.js',  array( 'acf-input' ), '', true);
    

    and this the contents of my JS file.

     jQuery( document ).ready( function( $ ) {
        if ( typeof acf !== 'undefined' ) {
            console.log( 'ACF is defined', acf );
        }
    
    });
    
    acf.add_action('load', function() {
        // Your code here
        var postID = acf.get('post_id');
        console.log(postID);
        //
    });
    
    

    in my console log i’m getting null from any field i try to read.

    `ACF is defined {data: {…}, get: ƒ, has: ƒ, set: ƒ, uniqueId: ƒ, …}
    sitewide.js?ver=6.3.1:14 null

    Any ideas where i’m going wrong here?

  • Some things are not clear.

    Let’s start with

    Are you trying to use this on the front end of the site or in the admin?

  • Hi John,

    This is in a JS file thats being enqueued in the themes functions.php

    It’s probably easier to tell you what i’m trying to achieve.

    I have a page that loads a custom post type called projects in a isotope.js grid.
    I’ve got some filtering going on using a URL hash. EG. /projects/#tag=green or /projects/#network=bbc

    that’s all handled in javascript.

    When a tag is loaded i want to be able to pull a title & an acf field from the taxonomy term of the tag “green” and update a classes innerhtml with the loaded data.

    As far as i’m aware php can’t access the hash and java is the way to do it.

  • The ACF JS API only runs in the admin while editing something that has ACF fields to edit. It cannot be used to get field values on the front end of the site.

  • Ah ok! That isn’t very clear on the documentation. Is there a way to get values via javascript on the front end?

  • There are a number of ways.

    1) You can use the WP REST API – I won’t be much help here.

    2) You can localize your JS. This is good for values that are static, always the same for the page. This will not work if values can change while any type of caching is enabled.

    3) You can write your own AJAX functions to get the values

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

You must be logged in to reply to this topic.