Support

Account

Home Forums Front-end Issues Conditionally Load Javascript Based on Presence of ACF Field Reply To: Conditionally Load Javascript Based on Presence of ACF Field

  • The acf/load_field hook is fired every time a field is referenced, even if that field has no value. This is not a good hook to use for this purpose. Generally you would to so when you output the value

    
    $value - get_sub_field('your-field');
    if ($value) {
      // enqueue script to be inserted in the page footer
    }
    

    But that will not help you. The file that you’re trying to enqueue is a CSS file which needs to be in the head of the html. There isn’t any way to know if a specific field nested that deep has a value in when it needs to be enqueued, you basically need to traverse the fields to discover this.

    The only option that I can think of is to use output JavaScript when the field is actually displayed that will dynamically insert the stylesheet link in the html head, but this seems like a lot of work.

    Another option is to insert a custom meta value not related to ACF when then post is saved if there is a value when the post is saved that indicates if the style sheet should be loaded on the page. Knowing this still requires traversing the fields to discover if that nested field has a value. Again, a lot of work.

    If this style sheet only has a few lines of CSS you’re probably better off just adding it to the sites main CSS file.