The gform_post_category_choices Gravity Forms PHP filter allows you to modify the post category field choices when the form markup is being prepared.
Table of contents
Usage
To apply your custom 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): A multidimensional array containing the choices and their properties. Example:
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.
More information
See Gravity Forms Docs: gform_post_category_choices
Examples
Sort the choices numerically
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'] );
}
Place this code in the functions.php file of your active theme.
This filter is located in GFCommon::add_categories_as_choices() in common.php.