Skip to content

Instantly share code, notes, and snippets.

@zakirsujon
Last active October 4, 2015 06:05
Show Gist options
  • Save zakirsujon/225bfe4e60af82a5d81c to your computer and use it in GitHub Desktop.
Save zakirsujon/225bfe4e60af82a5d81c to your computer and use it in GitHub Desktop.
Create a Advance Search using ACF input fields
<?php
/*
* Show ACF input fields in front-end to create a Advance Search
*/
// Load ACF scripts before header for executable or conditional fields
acf_form_head();
get_header(); ?>
<!-- Print ACF Fields with in form -->
<form method="GET" action="" id="acf-form">
<?php
acf_form( array(
'post_id' => YOUR_POST_ID, // set the post ID which have those field
'form' => false,
) );
?>
<input type="submit" value="GO">
</form>
<?php
if( isset( $_GET['acf'] ) ){
$fields = $_GET['acf'];
$keys = array_keys($fields); // get keys only like 'fields_1234567890123'
$value = array();
foreach ($keys as $key ) {
$field = get_field_object( $key ); // get object from each key
$value[$field['key']] = $field['name']; // set key with name
}
$meta = array_combine($value, $fields); // combine name with value from `#acf-form`
/*
* set meta key relation for custom meta query
* see- http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters
*/
$metas = array('relation' => 'AND');
// create array for `Multiple Meta Entries` on $metas
foreach ($meta as $meta_key => $meta_value) {
// remove those fields which don't have any value
if( !empty($meta_value) ){
$metas[] = array(
'key' => $meta_key,
'value' => $meta_value,
'compare' => 'LIKE',
);
}
}
// Query Posts from custom meta value
$args = array(
'post_type' => YOUR_CUSTOM_POST_TYPE, // like- 'post', 'page', 'book'
'meta_query' => $metas
);
$query = new WP_Query( $args );
if( $query->have_posts() ){
echo '<ul>';
while( $query->have_posts() ){ $query->the_post();
echo '<li><a href="'. get_permalink() .'">'. (get_the_title()?get_the_title():'(no-title)') .'</a></li>';
}
echo '</ul>';
wp_reset_query();
} else {
echo 'No result found';
}
}
?>
<!-- Remove ACF hidden fields from search query -->
<!-- First make sure your theme or plugin have jQuery included in header -->
<script type="text/javascript">
jQuery(document).ready(function($){
$('.acf-hidden').html('');
});
</script>
<?php get_footer(); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment