Skip to content

Function

Render an input setting field.

tml_admin_setting_callback_input_field( array $args )

Parameters

$args array
Optional. An array of arguments for rendering an input.
$label_for string
The input name/ID.
$value string
The input value.
$description string
A short description of the input.
$attributes array
An array of HTML attributes for the input.
$input_type string
The type of input. Default is "text".
$input_class string
The input class. Default is "regular-text".

Source

function tml_admin_setting_callback_input_field( $args ) {
    $args = wp_parse_args(
        $args,
        array(
            'label_for'   => '',
            'value'       => '',
            'description' => '',
            'attributes'  => array(),
            'input_type'  => 'text',
            'input_class' => 'regular-text',
        )
    );

    $attributes = is_array( $args['attributes'] ) ? array_filter( $args['attributes'] ) : array();

    if ( isset( $args['label_for'] ) ) {
        $attributes['name'] = $args['label_for'];
        $attributes['id']   = $args['label_for'];
    }
    if ( isset( $args['value'] ) ) {
        $attributes['value'] = $args['value'];
    }
    if ( isset( $args['input_type'] ) && empty( $attributes['type'] ) ) {
        $attributes['type'] = $args['input_type'];
    }
    if ( isset( $args['input_class'] ) && empty( $attributes['class'] ) ) {
        $attributes['class'] = $args['input_class'];
    }

    $attributes = array_map(
        function ( $key ) use ( $attributes ) {
            return is_bool( $attributes[ $key ] ) ? esc_attr( $key ) : sprintf( "%s='%s'", esc_attr( $key ), esc_attr( $attributes[ $key ] ) );
        },
        array_keys( $attributes )
    );

    usort(
        $attributes,
        function ( $a, $b ) {
            $x = strpos( $a, '=' ) === false;
            $y = strpos( $b, '=' ) === false;
            if ( $x && ! $y ) {
                return 1;
            }
            if ( $y && ! $x ) {
                return -1;
            }
            return strcmp( $a, $b );
        }
    );
    ?>

    <input <?php echo implode( ' ', $attributes ); /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- each attribute string is already built via esc_attr() above. */ ?>/>

    <?php if ( ! empty( $args['description'] ) ) : ?>
        <p class="description"><?php echo wp_kses_post( $args['description'] ); ?></p>
    <?php endif; ?>

    <?php
}

Uses

Changelog

VersionDescription
7.0 Introduced.