Support

Account

Home Forums ACF PRO WP archive with custom field filter : not working

Solved

WP archive with custom field filter : not working

  • hi,
    With acf5, i think there is a bug with creating a WP archive with custom field filter.
    I created exactly the same custom fields (bedrooms), pasted exactly the same code on page and function which are eplained on your documentation : http://www.advancedcustomfields.com/resources/tutorials/creating-wp-archive-custom-field-filter/

    It return on frontend :

    Notice: Undefined index: bedrooms
    on my page i have (exactly the same as on the documentation page):
    $field = get_field_object('bedrooms');

    Warning: Invalid argument supplied for foreach()
    the foreach loop is (exactly the same as on the documentation page):
    foreach( $field['choices'] as $choice_value => $choice_label ):

    the entire code :

    page-something.php

    <?php 
     
    	$field = get_field_object('bedrooms');
    	$values = explode(',', $_GET['bedrooms']);
     
    	?>
    	<ul>
    		<?php foreach( $field['choices'] as $choice_value => $choice_label ): ?>
    			<li>
    				<input type="checkbox" value="<?php echo $choice_value; ?>" <?php if( in_array($choice_value, $values) ): ?>checked="checked"<?php endif; ?> /> <?php echo $choice_label; ?></li>
    			</li>
    		<?php endforeach; ?>
    	</ul>

    functions.php

    add_action('pre_get_posts', 'my_pre_get_posts');
     
    function my_pre_get_posts( $query )
    {
    	// validate
    	if( is_admin() )
    	{
    		return;
    	}
     
    	if( !$query->is_main_query() )
    	{
    		return;
    	}
     
    	// get original meta query
    	$meta_query = $query->get('meta_query');
     
            // allow the url to alter the query
            // eg: http://www.website.com/events?location=melbourne
            // eg: http://www.website.com/events?location=sydney
            if( !empty($_GET['bedrooms']) )
            {
            	$bedrooms = explode(',', $_GET['bedrooms']);
     
            	//Add our meta query to the original meta queries
    	    	$meta_query[] = array(
                    'key'		=> 'bedrooms',
                    'value'		=> $bedrooms,
                    'compare'	=> 'IN',
                );
            }
     
    	// update the meta query args
    	$query->set('meta_query', $meta_query);
     
    	// always return
    	return;
     
    }

    Is the documentation page out of date?

    Thank you

  • Hi @hedi

    The PHP error you have listed states that there is no $_GET['bedrooms'] when loading the page.

    You will need to add some logic to determine if the bedrooms isset, which I have updated the linked documentation to do.

    Cheers
    E

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

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