Function and usage of checked() in wordpress

Question

Answers ( 1 )

    0
    2024-01-05T15:14:29+00:00

    The checked() function in WordPress is used primarily in forms, specifically for checkboxes and radio buttons. Its purpose is to output the HTML checked attribute based on the comparison of two values. This is particularly useful for ensuring that the correct items are marked as checked when a form is displayed, often in situations like settings pages or form submissions.

    Function Signature:

    checked( mixed $checked, mixed $current = true, bool $display = true ): string
    

    Parameters:

    1. $checked (mixed, required): This is one of the values to be compared. It's typically the value that you want to check against, like a setting or option value.

    2. $current (mixed, optional): This is the other value to compare. If not provided, it defaults to true. This value is usually the current state or value of the checkbox or radio button.

    3. $display (bool, optional): Determines whether to echo the result (output directly to the HTML) or just return it as a string. By default, it is set to true, meaning it will echo the checked attribute.

    Return Value:

    • String: It returns the HTML checked attribute (checked='checked') if the comparison is true, otherwise it returns an empty string.

    Functionality:

    • The function compares the first two arguments ($checked and $current).
    • If these values are identical, the function outputs checked='checked'.
    • If they are not identical, it outputs an empty string.

    Sample Usage:

    Let's consider a scenario where you have an options page in a WordPress plugin or theme, and you're displaying a checkbox.

    Example 1: Simple Checkbox

    <input type="checkbox" name="option_name" <?php checked( get_option('option_name'), 1 ); ?> value="1">
    

    In this example, get_option('option_name') retrieves the saved value for 'option_name' from the database. If it's 1, the checkbox will be checked.

    Example 2: Comparing Two Different Values

    <input type="checkbox" name="setting_name" <?php checked( get_setting('setting_name'), 'expected_value' ); ?> value="expected_value">
    

    Here, the checkbox will be checked if the value of get_setting('setting_name') is equal to 'expected_value'.

    Conclusion:

    The checked() function is a convenient way to manage the state of checkboxes and radio buttons in forms, ensuring that they reflect the current settings or user inputs. It simplifies the process of comparing values and dynamically setting the checked attribute in HTML.

Leave an answer