Support

Account

Home Forums Front-end Issues Reverse Query ACF Term "meta" Reply To: Reverse Query ACF Term "meta"

  • So I modified your solution with the intent making the value optional. I’m not very good with SQL so I doubt my use of the AND statement is the cleanest way to do that.

    
    function acf_get_terms( $args = array() ) {
      global $wpdb;
      $defaults = array(
        'taxonomy_slug'     => '',
        'acf_field_name'    => null,
        'meta_value'        => '',
      );
      $args = wp_parse_args( $args, $defaults );
    
      if ( empty($args['taxonomy_slug']) || ! taxonomy_exists( $args['taxonomy_slug'] ) || empty( $args['acf_field_name'] ) ) {
        return new WP_Error( 'invalid_option_name', __('ACF term meta names are formatted as {$term->taxonomy}_{$term->term_id}_{$field[\'name\']}.') );
      }
    
      $rows = $wpdb->get_results($wpdb->prepare(
          "
          SELECT option_name
          FROM {$wpdb->prefix}options
          WHERE option_name LIKE %s
          AND option_value LIKE %s
          ",
          $args['taxonomy_slug'] . '_%_' . $args['acf_field_name'],
          empty($args['meta_value']) ? '%' : $args['meta_value']
      ));
    
      $unit_ids = array();
    
      foreach( $rows as $row ){
          preg_match('/^' . $args['taxonomy_slug'] . '_(\d*)_' . $args['acf_field_name'] . '$/', $row->option_name, $matches);
          $unit_ids[] = $matches[1];
      }
    
      $terms = get_terms(array(
          'taxonomy' => $args['taxonomy_slug'],
          'hide_empty' => false,
          'include' => $unit_ids,
      ));
    
      return $terms;
    }