Creating a WP archive with custom field filter

Overview

This video tutorial will cover the basics of creating a WP archive that displays posts filtered by a checkbox custom field. Please watch the video first, and use the code below to kick start your project!

Code snippets

WP_Query args action

This snippet of code is placed within the functions.php file and modifies the WP_Query args based on the $_GET params available

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;

}

Checkbox for archive template

This snippet of code is placed within a template file that is shown on the archive page for your post type.

<div id="search-houses">
	<?php 

	$field = get_field_object('bedrooms');
	$values = isset($_GET['bedrooms']) ? explode(',', $_GET['bedrooms']) : array();

	?>
	<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('houses'); ?>?bedrooms=' + vals);

		console.log( vals );

	});

})(jQuery);	
</script>

Reference

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s