Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping the value of a select from wordpress loop

I am looking for a way to retain the selection from a a list of options which are created from within a WordPress post loop:

<?php 
$args = array( 'post_type' => 'office_locations', 'posts_per_page' => -1, 'order_by' => 'title', 'order' => 'ASC'  );
$loop = new WP_Query( $args ); ?>

<select style="width: 100%;"  name="selectedValue" onchange="this.form.submit()">

<option disabled>Select an office location...</option> // This is disabled
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<option><?php echo get_the_title();?></option>
<?php endwhile; ?>

</select>

So if a User makes a selection I have set it to post that upon selection, is there a way for the select to remain on that option after this happens?

like image 546
danjbh Avatar asked Dec 10 '25 12:12

danjbh


1 Answers

Sure, check the value of POST matches the value of the select, then set as selected:

<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
    <option<?= (isset($_POST['selectedValue']) && $_POST['selectedValue'] == get_the_title() ? ' selected' : null) ?>><?php echo get_the_title();?></option>
<?php endwhile; ?>
like image 126
Lawrence Cherone Avatar answered Dec 12 '25 02:12

Lawrence Cherone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!