I have been working through this example: http://ift.tt/1yr9ExS
That a colleague of mine found for creating a simple checkbox-based filter for Wordpress custom posts, that filters by a custom post type.
I've got it all set up and it seems to be working here - http://ift.tt/1CYqWlL , if you filter by 'Balcombe Place' then the 'All Locations' post is removed as you would expect.
However if you choose an option that isn't there, the filters disappear on the refresh and I cannot figure out why. My colleague has used this exact code on another site that doesn't have this problem so I'm left stumped. I've tried reordering the elements in the template in case something is affecting it but nothing seems to change.
The code in my archive-jobs.php :
<div class="filterOptions">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean nisl odio, efficitur non lorem ut, volutpat egestas tellus. Vestibulum suscipit sem mi, nec mattis tortor convallis in. Integer in blandit turpis, consectetur tincidunt dolor.</p>
<div id="search-location">
<?php
$field = get_field_object('location_choice');
$values = explode(',', $_GET['location_choice']);
?>
<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-location').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('jobs'); ?>?location_choice=' + vals);
console.log( vals );
});
})(jQuery);
</script>
</div>
Code from 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://ift.tt/WaHaZ0
// eg: http://ift.tt/1xafnZJ
if( !empty($_GET['location_choice']) )
{
$location_choice = explode(',', $_GET['location_choice']);
//Add our meta query to the original meta queries
$meta_query[] = array(
'key' => 'location_choice',
'value' => $location_choice,
'compare' => 'IN',
);
}
// update the meta query args
$query->set('meta_query', $meta_query);
// always return
return;
}
Any help would be much appreciated!
Aucun commentaire:
Enregistrer un commentaire