Support

Account

Home Forums General Issues Custom field for specific category

Solving

Custom field for specific category

  • Hello guys,

    First of all, thanks to Elliot Condon for his plugin.

    I’ve a question: Is it possible to create custom fields via ACF for a specific category ? I’m not talking about posts in specific category but directly in the category .. in administration under the description of category for exemple.

    But specificly for one category.

    Thnaks

  • There isn’t any built in rules in ACF to do what you’re looking for. You need to create your own location rule for this. This is explained here: http://www.advancedcustomfields.com/resources/custom-location-rules/

    For those looking to do this and other custom rules here is some code for this specific case:

    Step 1: Add custom type

    In this step I’m actually going to create a new group rather than put my rule under one of the existing groups.

    
    add_filter('acf/location/rule_types', 'acf_location_rules_types', 999);
    function acf_location_rules_types($choices) {
        // create a new group for the rules called Terms
        // if it does not already exist
        if (!isset($choices['Terms'])) {
            $choices['Terms'] = array();
        }
        // create new rule type in the new group
        $choices['Terms']['category_id'] = 'Category Name';
        return $choices;
    }
    

    Step 2: We can skip step 2 because we don’t need to create a custom operator

    Step 3: Add custom values

    
    add_filter('acf/location/rule_values/category_id', 'acf_location_rules_values_category');
    function acf_location_rules_values_category($choices) {
        // get terms and build choices
        $taxonomy = 'category';
        $args = array('hide_empty' => false);
        $terms = get_terms($taxonomy, $args);
        if (count($terms)) {
            foreach ($terms as $term) {
                $choices[$term->term_id] = $term->name;
            }
        }
        return $choices;
    }
    

    Step 4: Matching the rule

    
    add_filter('acf/location/rule_match/category_id', 'acf_location_rules_match_category', 10, 3);
    function acf_location_rules_match_category($match, $rule, $options) {
        if (!isset($_GET['tag_ID']) || 
                !isset($_GET['taxonomy']) || 
                $_GET['taxonomy'] != 'category') {
            // bail early
            return $match;
        }
        $term_id = $_GET['tag_ID'];
        $selected_term = $rule['value'];
        if ($rule['operator'] == '==') {
            $match = ($selected_term == $term_id);
        } elseif ($rule['operator'] == '!=') {
            $match = ($selected_term != $term_id);
        }
        return $match;
    }
    
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Custom field for specific category’ is closed to new replies.