gform_post_category_choices

Description

The “gform_post_category_choices” filter in Gravity Forms can be used to alter the post category field choices when the form markup is being prepared.

Usage

The following would apply your function to all forms.

add_filter( 'gform_post_category_choices', 'your_function_name', 10, 3 );

To target a specific form append the form id to the hook name. (format: gform_post_category_choices_FORMID)

add_filter( 'gform_post_category_choices_5', 'your_function_name', 10, 3 );

To target a specific field on a specific form append the form id and the field id to the hook name. (format: gform_post_category_choices_FORMID_FIELDID)

add_filter( 'gform_post_category_choices_5_10', 'your_function_name', 10, 3 );

Parameters

  • $choices array

    An multidimensional array containing the choices and their properties.

array(
    array(
        'text'  => 'cat name 1',
        'value' => 'cat id 1',
    ),
    array(
        'text'  => 'cat name 2',
        'value' => 'cat id 2',
    ),
)
  • $field Field Object

    The current post category field.

  • $form_id int

    The ID of the current form.

Examples

1. Sort the choices

This example demonstrates how to sort the choices numerically.

add_filter( 'gform_post_category_choices_5_10', function ( $choices, $field, $form_id ) {
    // usort calls a custom sort function you create.
    usort( $choices, 'sort_numerically' );

    return $choices;
}, 10, 3 );
function sort_numerically( $a, $b ) {
    return floatval( $a['text'] ) > floatval( $b['text'] );
}

Placement

This code should be placed in the functions.php file of your active theme.

Source Code

This filter is located in GFCommon::add_categories_as_choices() in common.php.