Home Forums Front-end Issues Save select option on page refresh


Save select option on page refresh

  • Hi!)

    How can I save select option’s value on page refresh?

    It’s my code

    	global $wpdb;
    	$years = $wpdb->get_results( 'SELECT DISTINCT meta_value FROM wp_postmeta WHERE meta_key LIKE "press"', OBJECT );
    	<div class="filtering">
    		<select class="years-filter" name="years" id="years">
    			<option value="All">All years</option>
    			<?php foreach($years as $key => $value) :
    					foreach($value as $year) : 
    						<option value="<?php echo $year; ?>"><?php echo $year; ?></option>';
    			<?php endforeach;
    				endforeach; ?>
    			(function($) {
    				$('#years').on('change', function() {
    					var $val = $(this).closest('select'),
    						vals = [];
    				$val.find('option:selected').each(function() {
    					vals.push( $(this).val() );
    				vals = vals.join(',');
    				window.location.replace('<?php echo home_url('press'); ?>?press=' + vals);

    For example if I choose in dropdown 2017 year, page will refresh and show for me only posts which have 2017 value in custom field, but dropdown option return to All Years value.

    And second question, how can I show all posts(with 2016, 2017, empty field) on “All Years” option value?


  • For the first question, I’m not sure how the value is being submitted so I’m assuming that $_GET[‘press’] is an array of the selected values, if this assumption is incorrect then you’ll need to alter that part to match the submitted value.

    foreach ($years as $key => $value) {
      foreach ($value as $year) {
          <option value="<?php echo $year; ?>"<?php 
            if (in_array($year, $_GET['press'])) {
              echo ' selected="selected";
            ?>><?php echo $year; ?></option>

    To show the posts for the selected years you need to create a pre_get_posts filter that alters the WP query. Check out some of these topics on using pre_get_posts

  • @hube2 Thanks!

    Now it’s working, but how I can add option – “All Years” and show all posts when it’ll selected?

  • I’m only guessing again since there is no code. But all years has a value of “All” so if that’s the value submitted then you should not add anything to the query to filter posts by the year.

    As far as showing all posts, this is done by setting the query argument posts_per_page to -1

Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘Save select option on page refresh’ is closed to new replies.