0

I am capturing a month in my database and the value (integer) is being recorded but when I try to add the selected to the drop down so when the user comes back it reflects the month I can't figure out what I need to set the drop down to reflect the integer value that was previously submitted. If someone can share what i am missing in my selected code I would really appreciate it.

    $months = array(
        1=>'January',
        2=>'February',
        3=>'March',
        4=>'April',
        5=>'May',
        6=>'June',
        7=>'July',
        8=>'August',
        9=>'September',
        10=>'October',
        11=>'November',
        12=>'December'
    );

    $birth_date_month = get_the_author_meta( 'birth_date_month', $user->ID );

    <?php
    foreach ( $months as $num => $month ) {
        printf('<option value="%u">%s</option>', $num, $month, selected( $birth_date_month, $num, false ) );
    }
    ?>
  • 1
    It's not possible to tell what the value of birth_date_month would be from the code you've given, the save code would be necessary. But since you have access to the code, could you not just do echo $birth_date_month and look? – Tom J Nowell Feb 16 at 0:47
0

You're not actually outputting the selected attribute into the <option> tag. Look at your printf() format:

'<option value="%u">%s</option>'

%u is there for the month's number value, and %s is there for month's name, but you're not including the last argument from the result of selected().

Your printf() needs to look like this:

printf(
    '<option value="%u" %s>%s</option>', 
    $num, 
    selected( $birth_date_month, $num, false ), 
    $month
);

Note that I swapped the order of the arguments, because selected needs to be output before the month name.

  • Thank you for your help. That was exactly what it needed. – user3692010 Feb 18 at 15:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.