Skip to content

Instantly share code, notes, and snippets.

@claygriffiths
Created December 16, 2021 17:28
Show Gist options
  • Save claygriffiths/5dc9225179d90853558b86efa499c70b to your computer and use it in GitHub Desktop.
Save claygriffiths/5dc9225179d90853558b86efa499c70b to your computer and use it in GitHub Desktop.
Gravity Forms: Get Field by Label
<?php
/**
* Get Gravity Forms Field by Label
* @link https://gravitywiz.com
*
* @param array|int $form_or_id The Form Object or ID.
* @param string $search The field label to search by.
* @param string $label_property The property from the field to search using. Defaults to "label". Set to "adminLabel"
* to search by the admin label.
*
* @returns GF_Field|null
*
* @example
* // Search for "Paragraph Text B" label in form ID 1.
* gw_get_field_by_label(1, 'Paragraph Text B');
*
* @example
* // Search for "Testing 123" admin label in form ID 2.
* gw_get_field_by_label(2, 'Testing 123', 'adminLabel');
*/
function gw_get_field_by_label( $form_or_id, $search, $label_property = 'label' ) {
if ( ! class_exists( 'GFAPI' ) ) {
return null;
}
$form = is_numeric( $form_or_id ) ? GFAPI::get_form( $form_or_id ) : $form_or_id;
/** @var GF_Field $field */
foreach ( $form['fields'] as $field ) {
if ( rgar( $field, $label_property ) === $search ) {
return $field;
}
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment