Description
The gform_post_category_choices filter in Gravity Forms can be used to alter the post category field choices during form markup preparation.
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
| Parameter | Type | Description |
|---|---|---|
$choices | array | A multidimensional array containing the choices and their properties. |
$field | Field Object | The current post category field. |
$form_id | int | The ID of the current form. |
The $choices array is formatted as follows:
array(
array(
'text' => 'cat name 1',
'value' => 'cat id 1',
),
array(
'text' => 'cat name 2',
'value' => 'cat id 2',
),
)
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 can be used in the functions.php file of the active theme, a custom functions plugin, a custom add-on, or with a code snippets plugin.
See also the PHP section in this article: Where Do I Put This Code?
Source Code
This filter is located in GFCommon::add_categories_as_choices() in common.php.