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

ParameterTypeDescription
$choicesarrayA multidimensional array containing the choices and their properties.
$fieldField ObjectThe current post category field.
$form_idintThe 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.