Support

Account

Home Forums ACF PRO Dynamically grab the category of a product in a hidden field Reply To: Dynamically grab the category of a product in a hidden field

  • The only way I can think of to do this is using a combination of things ACF fillters, JavaScript and CSS.

    See https://www.advancedcustomfields.com/resources/adding-custom-javascript-fields/

    To hide the field you would have to add CSS to the admin, this is the only way to hide a field in ACF and still have the field submitted. The best solution would be a text field. Unless you don’t want it submitted. If this is the case you could set some conditional logic that can never be met.

    You will need to choose a default value for this hidden field and add an acf/prepare_field to set the field value. In this filter you can get the global $post get the catetory of the post and then get the top level category. There are various ways that this can be done. Then use this to set the value of the field. If it is a new post then the category will be empty and you would set a default value.

    With that in place you would create your other fields that are conditional on the value of this hidden field.

    Then you need to add custom JavaScript that will detect when the category is changed and update the value of this hidden field so that it can cause ACF to show the correct fields. I would likely localize the script and include an array of categories with their associated top level categories

    
    array(
      'category' => 'top_level_category',
      'category' => 'top_level_category',
      'category' => 'top_level_category',
      'category' => 'top_level_category',
      'category' => 'top_level_category',
      'category' => 'top_level_category',
      'category' => 'top_level_category',
    )
    

    so that I can use the JS array to look up the value rather than trying to do an AJAX request to get the top level category when a change is made.