Hello everybody. Help me please.
Made a filter according to the instructions: WP archive with custom field filter
Everything works, but when the posts are not found, the “select” is empty.
How to make filter options always appear, even if there are no posts?
function.php:
$GLOBALS['my_query_filters'] = array(
'field_1' => 'city',
'field_2' => 'vac'
);
add_action('pre_get_posts', 'my_pre_get_posts', 10, 1);
function my_pre_get_posts( $query ) {
if( is_admin() ) return;
if( !$query->is_main_query() ) return;
$meta_query[] = $query->get('meta_query');
foreach( $GLOBALS['my_query_filters'] as $key => $name ) {
if( !empty($_GET[ $name ]) ) {
$value = explode(',', $_GET[ $name ]);
$meta_query[] = array(
'key' => $name,
'value' => $value,
'compare' => 'IN',
);
}
}
$query->set('meta_query', $meta_query);
return;
}
HTML:
<div id="search-houses">
<?php
$field = get_field_object('city');
$values = explode(',', $_GET['city']);
?>
<div class="filterss">
<div class="filter" data-filter="city">
<select class="city">
<option value="">Region</option>
<?php foreach( $field['choices'] as $choice_value => $choice_label ): ?>
<option value="<?php echo $choice_value; ?>" <?php if( in_array($choice_value, $values) ): ?>selected<?php endif; ?> /> <?php echo $choice_label; ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
</div>
<div class="columns-container vacc">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php get_template_part('loop-v'); ?>
<?php endwhile; ?>
<?php else: echo 'Not Found.
'; ?>
<?php endif; ?>
</div>