Make WordPress Core

Opened 9 years ago

Closed 9 years ago

Last modified 9 years ago

#35268 closed enhancement (wontfix)

Allow comparison of multiple values for checked(), selected(), and disabled()

Reported by: kingkool68's profile kingkool68 Owned by:
Milestone: Priority: normal
Severity: normal Version:
Component: Formatting Keywords: has-patch has-unit-tests
Focuses: Cc:

Description

The aim of this ticket is to make these convenience functions a little more convenient by allowing the comparison of multiple values for checked(), selected(), disabled(). Take the following use case of a form asking you to select days of the week:

Testing the value with if():

<?php
$days = array( 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', );
$selected_days = array( 'Monday', 'Wednesday', 'Friday', );
foreach ( $days as $day ) { ?>
    <label><input type="checkbox" name="days[]" value="<?php echo esc_attr( $day ); ?>" <?php if ( in_array( $day, $selected_days ) ) echo 'checked="checked"'; ?>><?php echo $day; ?></label>
<?php } ?>

Using checked() instead:

<?php
$days = array( 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', );
$selected_days = array( 'Monday', 'Wednesday', 'Friday', );
foreach ( $days as $day ) { ?>
    <label><input type="checkbox" name="days[]" value="<?php echo esc_attr( $day ); ?>" <?php checked( $selected_days, $day ); ?>><?php echo $day; ?></label>
<?php } ?>

Attachments (1)

35268-1.diff (2.7 KB) - added by kingkool68 9 years ago.

Download all attachments as: .zip

Change History (5)

@kingkool68
9 years ago

#1 @kingkool68
9 years ago

  • Keywords has-patch has-unit-tests added

Related: #22409, #10556

Last edited 9 years ago by kingkool68 (previous) (diff)

#2 follow-up: @johnbillion
9 years ago

  • Component changed from General to Formatting
  • Keywords close added

Thanks for the patch @kingkool68, but I don't believe we need any changes here. You can do this currently by passing in_array() to checked():

<input type="checkbox" <?php checked( in_array( $day, $selected_days ) ); ?>>

#3 in reply to: ↑ 2 @kingkool68
9 years ago

  • Resolution set to wontfix
  • Status changed from new to closed

Replying to johnbillion:

Thanks for the patch @kingkool68, but I don't believe we need any changes here. You can do this currently by passing in_array() to checked():

<input type="checkbox" <?php checked( in_array( $day, $selected_days ) ); ?>>

Ah that is pretty clever. I didn't think to do it that way. Thanks!

#4 @TobiasBg
9 years ago

  • Keywords close removed
  • Milestone Awaiting Review deleted
Note: See TracTickets for help on using tickets.