Support

Account

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

Solved

Save select option on page refresh

  • Hi!)

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

    It’s my code

    	<?php 
    	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; ?>
    		</select>
    		<script>
    			(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);
    				});
    			})(jQuery);
    		</script>
    	</div>

    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?

    Thanks!!!

  • 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>
        <?php 
      }
    }
    

    To show the posts for the selected years you need to create a pre_get_posts filter that alters the WP query. https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts. Check out some of these topics on using pre_get_posts https://support.advancedcustomfields.com/forums/search?bbp_search=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)

You must be logged in to reply to this topic.