selected

Home » Functions » selected

Function Name: selected

The selected function is a WordPress function that is used to determine whether an option should be marked as selected in a select element. It takes two arguments, the first is the current value and the second is the value that should be checked against. If both values match, the function returns a string containing the "selected" attribute. If not, it returns an empty string.

This function is commonly used in WordPress plugin and theme development when creating forms with select elements. It allows developers to dynamically mark an option as selected based on the current value, which can be useful for things like settings pages or custom post type archives.

Example Usage:

Let’s say we have a select element with a list of colors that a user can choose from. We want to mark the current color as selected when the form is loaded. We can use the selected function to accomplish this:

<select name="color">
  <option value="red" <?php echo selected( $current_color, 'red' ); ?>>Red</option>
  <option value="green" <?php echo selected( $current_color, 'green' ); ?>>Green</option>
  <option value="blue" <?php echo selected( $current_color, 'blue' ); ?>>Blue</option>
</select>

In this example, $current_color is the current value of the select element. We use the selected function to check whether each option’s value matches $current_color, and if so, add the "selected" attribute to that option.

Learn More on WordPress.org

Register an account to save your snippets or go Pro to get more features.