Support

Account

Home Forums General Issues Setting up front end filtering and sorting by custom fields

Solving

Setting up front end filtering and sorting by custom fields

  • Hi, I’m working on a site here: http://tlc.mainteractivegroup.com/find-my-apartment/

    I need to set up some filtering and sorting. The SELECT boxes need to be filters based on custom field input. I still have to tweak how the data is input, but you should get the idea.

    The column headings need to sort ASC/DSC by that column when clicked.

    I tried searching for over an hour on google yesterday and most of the info was for setting up column sorting on the WP-Admin side.

    If anyone can help me get pointed in the right direction as to how to do both the filtering and sorting by custom field values, I would be forever grateful.

    Thanks!

  • Hi there,

    I would start by checking out this tutorial => http://www.advancedcustomfields.com/resources/tutorials/creating-wp-archive-custom-field-filter/

    It shows you how to setup a filter based on a custom field that you should be able to adapt to your needs.

  • Ok so I went through that tutorial – bedrooms was already one of the fields I need to sort by, so I thought it would be easy – however, I am having a lot of trouble with this still.

    This is the code I put in my functions file:

    add_action('pre_get_posts', 'my_pre_get_posts');
     
    function my_pre_get_posts( $query ) {
    
        if( is_admin() ) { return; }
     
        $meta_query = $query->get('meta_query'); // get original meta query
        
        
        // validate type
        if( empty($_GET['bedrooms']) )
        {
    	    return;
        }
        
        
        // get types as an array
        // - use explode to get an array of values from type=a|b|c
        $bedrooms = explode('|', $_GET['bedrooms']);
        
        
        // set compare for the meta_query
        // - http://codex.wordpress.org/Class_Reference/WP_Query
        $meta_query['relation'] = 'OR';
        
        
        foreach( $bedrooms as $bedroom )
        {
    	    $meta_query[] = array(
                'key'       => 'bedrooms',
                'value'     => '"' . $bedroom . '"',
                'compare'   => 'LIKE',
            );
        }
    	
    	
        $query->set('meta_query', $meta_query); // update the meta query args
        
        return; // always return
    }
    

    This is the code I have on the page I want to have filtering:

    <div id="search-houses">
    <?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>
    </div>
    <script type="text/javascript">
    (function($) {
     
    	$('#search-houses').on('change', 'input[type="checkbox"]', function(){
     
    		// vars
    		var $ul = $(this).closest('ul'),
    			vals = [];
     
    		$ul.find('input:checked').each(function(){
     
    			vals.push( $(this).val() );
     
    		});
     
    		vals = vals.join(",");
     
    		window.location.replace('<?php echo home_url('find-my-apartment'); ?>?bedrooms=' + vals);
     
    		console.log( vals );
     
    	});
     
    })(jQuery);	
    </script>
    

    This is the page: http://tlc.mainteractivegroup.com/find-my-apartment/

    The first problem is that it is giving me a PHP error on this line:<?php foreach( $field['choices'] as $choice_value =>

    The second problem is, when I add ?bedrooms=3 or any other number to the URL it goes to a 404 page.

    The third thing I noticed – don’t know if this matters or not but when I add ?post_type=apartment to the URL it brings up the page just fine.

    So I really need some help getting this part at least functional. I also don’t really understand completely how this function interacts with the existing loop I have on the page. You can see below the PHP error I have a loop that displays out all the apartments with the custom fields. Do I need to do anything to change that loop for this to work?

    Thanks in advance!

  • Hi @lewmaster

    The first thing I noticed is that your pre_get_posts filter uses this code:

    
    $bedrooms = explode('|', $_GET['bedrooms']);
    

    This should be:

    
    $bedrooms = explode(',', $_GET['bedrooms']);
    

    Please debug your code line by line to make sure all variables are correct and that your output is as desired.

    Thanks
    E

  • Thanks so much for getting back to me. I switched the | back to a , and double checked my variables and it looks basically just like the sample code. I am still getting the same error. It is on this line

    foreach( $field['choices'] as $choice_value => $choice_label ):

    I’m not sure what ‘choices’ is supposed to be.

    Also – I maybe didn’t mention this before but this is pulling from a custom post type rather than regular posts. Does that make a difference?

  • Ok so I did make a little progress on this.

    I set up a second instance of the site on another server to do some further testing.

    I was finally able to get it to somewhat work here: http://sandbox.webcontempodata.com/?bedrooms=2

    It correctly pulls the data and formats it the way I want it. The only way I could get it to work was by not assigning a custom home page – so that it uses index.php to pull homepage content, and then I added the code from my original apartment finder home page to index.php.

    So I guess the main question is: how do I get it to work just like this, but on an interior page like this: http://tlc.mainteractivegroup.com/find-my-apartment/

    Also – any idea why I would be getting the PHP error on one site and not on the other when they both are set up the same?

  • Hi @lewmaster
    It looks liek the issue is coming from the ACF field not being found. Can you please debug the $field variable like so:

    
    $field = get_field_object('bedrooms');
    echo '<pre>';
    	print_r( $field );
    echo '</pre>';
    

    My guess is that ACF does not know where to find the field. The get_field_object function will only work if a value has already been saved to the current $post.

    If your code is not run on single post page, then ACF will not be able to load the field. Perhaps you will need to change bedrooms to the field_key.

    using the field_key removes the need to lookup the value => key relationship.

    Thanks
    E

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

The topic ‘Setting up front end filtering and sorting by custom fields’ is closed to new replies.