Search code examples
wordpressadvanced-custom-fields

Query categories on ACF Taxonomy


I have created a custom field (taxonomy) on the category object, in order to categorize the categories, so to speak. But I don't know how to query categories based on this custom field.

My custom field is called "custom_parent" and the slug for the chosen value is "sport-fritid-parent".

Does anyone know what I'm doing wrong?

 $args = array(
 'tax_query' => array(
         array (
        'taxonomy' => 'custom_parent',
        'field' => 'slug',
        'terms' => 'sport-fritid-parent'
      )
    )
  );
  $c = get_categories($args);
  foreach($c as  $cat){
       echo $cat->name;

  }

Solution

  • To fetch terms of taxonomies( in your case category ) based on a custom field (or meta). You can use Meta Query

    For your case: this code should work fine.

    $args = [
       'meta_query' => [
          [
             'key'      => 'custom_parent',
             'value'    => 'sport-fritid-parent',
             'compare'  => '='
          ]
       ],
    ];
    
    $c = get_categories($args);
    foreach($c as  $cat){
        echo $cat->name;
    }