0

I'm currently using Advanced Custom Fields and I was wondering if anyone know how to filter categories by custom fields? I have a custom field in my categories using the checkboxes field. I want to make a page that will list categories that contain a specific checkbox field that is ticked. For example I have 3 checkboxes in my categories which are Romance,Action & Drama. I have ticked checkbox Action and I want to list categories on the page that have ticked checkbox Drama.

It is kind of similar to this tutorial http://www.advancedcustomfields.com/resources/how-to/how-to-query-posts-filtered-by-custom-field-values/ except I want to get categories instead of posts. What’s the easiest way to do this cause I’m not a programmer?

1
+50

Try something like this :

   $value = get_field('field_name');

Try whole process based on this http://www.advancedcustomfields.com/resources/how-to/filter-posts-by-custom-fields/

   $value = get_field('field_name', $category->cat_ID);
3

The issue is that there is no taxonomy meta data like there is for posts. ACF taxonomy data is stored serialized in the options table, so it can't be queried like post meta can. You have to load all terms and check the data associated to each one individually.

Perhaps a better solution is to create Romance, Action, & Drama parent terms, and make your other terms children of one of those parents.

1

If you have a lot of categories it will be a pain to search everytime every category and check against the field value.

I wrote something and I would love to know if it's correct or not

1st I wrote a function that get the option name from the value since wordpress core provide only a function that get the option value from name

function get_option_name_by_value( $option, $default = false ) {
  global $wpdb;

  $option = trim( $option );
  if ( empty( $option ) )
    return false;

  $name = wp_cache_get( $option, 'options_names' );

  if ( false === $name ) {
    $row = $wpdb->get_row( $wpdb->prepare( "SELECT option_name FROM $wpdb->options WHERE option_value = %s LIMIT 1", $option ) );
    // Has to be get_row instead of get_var because of funkiness with 0, false, null values
    if ( is_object( $row ) ) {
        $name = $row->option_name;
        wp_cache_add( $option, $name, 'options' );
    } else return false;
  }
  return $name;
}

and since the option name have the term id on it (taxonomy_termId_filedName), it's simple to get the term id simply by an explode('_',$optionName)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.