Home Forums General Issues WP archive with custom field filter


WP archive with custom field filter

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


    $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);


    <div id="search-houses">
                   $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; ?>
             <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; ?>
  • Use the field key here instead of the field name

    $field = get_field_object('city');

    The reason why is because of the current post does not have any values then ACF does not know how to get the field object. ACF uses a combination of the field name and the post ID to look up the field key, when there is not value ACF cannot find the field key and cannot get the field object.

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

The topic ‘WP archive with custom field filter’ is closed to new replies.