search

Home  >  Q&A  >  body text

Why is the selected drop-down box value not displayed?

I'm building a function for my WordPress plugin that will display a dropdown list of all available pages. When I click "Save Changes" the values ​​are saved in the database perfectly. It also updates the value perfectly. However, the selected value is not displayed in the dropdown list. When "Save Changes" is clicked, the values ​​are saved, but the dropdown is reset to "Select One" again. It cannot display the selected option. Am I doing something wrong here? Any guidance would be greatly appreciated.

<form method=post>
<div class="header-right">
  <?php
  $posts = get_pages(
    array(
        'post_status' => 'publish',
    )
  );
  
  ?>
  <select name="page_for_logged_in" id="page_for_logged_in">
    <option selected="selected">选择一个</option>
    <?php
    foreach ( $posts as $page ) {
        ?>
        <option value="<?php echo esc_attr( $page->post_name ); ?>" <?php selected(get_option('page_for_logged_in'), 'page')?>><?php echo esc_html( $page->post_title ); ?></option>
        <?php
    }
    ?>
  </select>

  <?php
  if(empty($_POST['page_for_logged_in'])) {
      
    } else {
      $myvalue=$_POST['page_for_logged_in'];
      update_option('page_for_logged_in', $myvalue, $autoload = 'no');
    }
    ?>

<?php submit_button(); ?>

</p>
</br>
</br>
</form>

P粉090087228P粉090087228433 days ago700

reply all(1)I'll reply

  • P粉197639753

    P粉1976397532023-09-13 12:24:36

    Ok, so I found a solution to my problem. Below is the pasted code; it may be helpful to someone.

    <form method=post>
        <div class="header-right">
          <?php
          $posts = get_pages(
            array(
                'post_status' => 'publish',
            )
          );
          
          ?>
          <?php
          if(empty($_POST['page_for_logged_in'])) {
              
            } else {
              $myvalue=$_POST['page_for_logged_in'];
              update_option('page_for_logged_in', $myvalue, $autoload = 'yes');
            }
            ?>
          <select name="page_for_logged_in" id="page_for_logged_in">
            <option value="" disabled selected>选择一个</option>
            <?php
            foreach ( $posts as $page ) {
                ?>
            <option value="<?php echo esc_attr( $page->post_title ); ?>" <?php echo ( get_option('page_for_logged_in') == $page->post_title ? 'selected' : '' ); ?>><?php echo esc_html( $page->post_title ); ?></option>
                <?php
            }
            ?>
          </select>
    
        <?php submit_button(); ?>
    
        </p>
        </br>
        </br>
        </form>

    reply
    0
  • Cancelreply