Skip to content

Instantly share code, notes, and snippets.

@Farmatique
Last active February 4, 2020 13:59
Show Gist options
  • Save Farmatique/308e16b4d85e214b6af86b02f94d8338 to your computer and use it in GitHub Desktop.
Save Farmatique/308e16b4d85e214b6af86b02f94d8338 to your computer and use it in GitHub Desktop.
Wordpress: Search in ACF fields loop
<form method="GET" action="/url-of-your-current-page/">
<input type="text" name="search" class="search-string" placeholder="">
<a class="search-clear"><i class="fa fa-times-circle" aria-hidden="true"></i>
</a>
<button type="submit">Search</button>
</form>
//search block js
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}
jQuery('input[name="search"]').attr('placeholder', getUrlParameter('search'));
jQuery('.search-clear').click(function(e){
e.preventDefault();
window.location.href = window.location.href.split('?')[0];
})
//php template
<?php
$search_str = get_query_var('search') ? get_query_var('search') : '';
// filter for searching in post-titles only
function title_filter($where, &$wp_query){
global $wpdb;
if($search_term = $wp_query->get( 'title_filter' )){
$search_term = $wpdb->esc_like($search_term); //instead of esc_sql()
$search_term = ' \'%' . $search_term . '%\'';
$title_filter_relation = (strtoupper($wp_query->get( 'title_filter_relation'))=='OR' ? 'OR' : 'AND');
$where .= ' '.$title_filter_relation.' ' . $wpdb->posts . '.post_title LIKE '.$search_term.' AND post_type = "customers"';
}
return $where;
};
add_filter('posts_where','title_filter',10,2);
// args for searching in ACF and post-title (using title_filter)
$args = array(
'post_type' => 'customers',
'posts_per_page' => -1,
'orderby' => 'menu_order title',
'order' => 'ASC',
'post_status' => 'publish',
'post__not_in' => array(665356),
'title_filter' => $search_str,
'title_filter_relation' => 'OR',
'meta_query' => array(
array(
'key' => 'case_study_text',
'value' => $search_str,
'compare' => 'LIKE'
),
'relation' => 'OR'
)
);
$the_query = new WP_Query($args);
if ($the_query->have_posts()):
while ($the_query->have_posts()) :
$the_query->the_post();
$post_id = get_the_ID();
$the_post = get_post($post_id);
?>
...
<?php endwhile; endif;?>
<?php wp_reset_query(); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment