Creating a WP archive with custom field filter


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() )

	if( !$query->is_main_query() )

	// get original meta query
	$meta_query = $query->get('meta_query');

        // allow the url to alter the query
        // eg:
        // eg:
        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


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">

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

		<?php foreach( $field['choices'] as $choice_value => $choice_label ): ?>
				<input type="checkbox" value="<?php echo $choice_value; ?>" <?php if( in_array($choice_value, $values) ): ?>checked="checked"<?php endif; ?> /> <?php echo $choice_label; ?></li>
		<?php endforeach; ?>
<script type="text/javascript">
(function($) {

	$('#search-houses').on('change', 'input[type="checkbox"]', function(){

		// vars
		var $ul = $(this).closest('ul'),
			vals = [];


			vals.push( $(this).val() );


		vals = vals.join(",");

		window.location.replace('<?php echo home_url('houses'); ?>?bedrooms=' + vals);

		console.log( vals );





Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s