acf_field_button_group::render_field │ public │ ACF 5.6.3

Creates the field's input HTML

Method of the class: acf_field_button_group{}

No Hooks.

Returns

null. Nothing (null).

Usage

$acf_field_button_group = new acf_field_button_group();
$acf_field_button_group->render_field( $field );
$field(array) (required)
The field settings array.

Changelog

Since 5.6.3 Introduced.

acf_field_button_group::render_field() code ACF 6.8.8

public function render_field( $field ) {

	// vars
	$html     = '';
	$selected = null;
	$buttons  = array();
	$value    = esc_attr( $field['value'] );

	// bail ealrly if no choices
	if ( empty( $field['choices'] ) ) {
		return;
	}

	// buttons
	foreach ( $field['choices'] as $_value => $_label ) {

		// checked
		$checked = ( $value === esc_attr( $_value ) );
		if ( $checked ) {
			$selected = true;
		}

		// append
		$buttons[] = array(
			'name'         => $field['name'],
			'value'        => $_value,
			'label'        => $_label,
			'checked'      => $checked,
			'button_group' => true,
		);
	}


	// maybe select initial value
	if ( ! $field['allow_null'] && $selected === null ) {
		$buttons[0]['checked'] = true;
	}

	// Ensure roving tabindex when allow_null is enabled and no selection yet.
	if ( $field['allow_null'] && $selected === null && ! empty( $buttons ) ) {
		$buttons[0]['tabindex'] = '0';
	}

	// div
	$div = array(
		'class' => 'acf-button-group',
		'role'  => 'radiogroup',
	);

	// Add aria-labelledby if field has an ID for proper screen reader announcement
	if ( ! empty( $field['id'] ) ) {
		$div['aria-labelledby'] = $field['id'] . '-label';
	}

	if ( 'vertical' === $field['layout'] ) {
		$div['class'] .= ' -vertical';
	}
	if ( $field['class'] ) {
		$div['class'] .= ' ' . $field['class'];
	}
	if ( $field['allow_null'] ) {
		$div['data-allow_null'] = 1;
	}

	// hdden input
	$html .= acf_get_hidden_input( array( 'name' => $field['name'] ) );

	// open
	$html .= '<div ' . acf_esc_attrs( $div ) . '>';

	// loop
	foreach ( $buttons as $button ) {

		// checked
		if ( $button['checked'] ) {
			$button['checked'] = 'checked';
		} else {
			unset( $button['checked'] );
		}

		// append
		$html .= acf_get_radio_input( $button );
	}

	// close
	$html .= '</div>';

	// return
	echo $html; //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- safe HTML, escaped by input building functions.
}