Skip to content

Function

Render a dropdown setting field.

tml_admin_setting_callback_dropdown_field( array $args )

Parameters

$args array
Optional. An array of arguments for rendering a dropdown.
$label_for string
The dropdown name/ID.
$options array
An array of options for the dropdown.
$selected string
The value of the selected option.
$description string
A short description of the dropdown.

Source

function tml_admin_setting_callback_dropdown_field( $args ) {
    $args = wp_parse_args(
        $args,
        array(
            'label_for'   => '',
            'options'     => array(),
            'selected'    => '',
            'description' => '',
        )
    );

    $options = array();
    foreach ( (array) $args['options'] as $value => $label ) {
        $options[] = sprintf(
            '<option value="%1$s"%2$s>%3$s</option>',
            esc_attr( $value ),
            selected( $args['selected'], $value, false ),
            esc_html( $label )
        );
    }
    ?>

    <select name="<?php echo esc_attr( $args['label_for'] ); ?>" id="<?php echo esc_attr( $args['label_for'] ); ?>">
        <?php echo implode( "<br />\n", $options ); /* phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- each $options entry is already built via esc_attr()/esc_html() above. */ ?>
    </select>

    <?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.