custom field – Extend search query to search meta keys values based on search string
I want to create an autocomplete AJAX search and I’m trying to have it where when the user starts typing, the list populates titles matching that search string.
My issue is in the WP_query, because I want to search the title, content and search meta key values and show the results. I will be searching the rfi_antenna_sku
meta key and alive_antenna_sku
meta key, etc for the product
post type.
My Query:
// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
$args = array(
'posts_per_page' => -1,
's' => esc_attr( $_POST['keyword'] ),
'post_type' => array('product'),
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'rfi_antenna_sku',
'value' => esc_attr( $_POST['keyword'] ),
'compare' => 'LIKE',
),
array(
'key' => 'alive_antenna_sku',
'value' => esc_attr( $_POST['keyword'] ),
'compare' => 'LIKE',
)
)
);
$the_query = new WP_Query( $args );
if( $the_query->have_posts() ) :
echo '<ul>';
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<li><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></li>
<?php endwhile;
echo '</ul>';
wp_reset_postdata();
endif;
die();
}
In case it helps future people, here’s the rest:
function antennas_competitive_search_form() {
$output="<div class="search_bar">";
$output .= '<form action="/" method="get" autocomplete="off">';
$output .= '<input type="text" name="s" placeholder="Search Code..." id="keyword" class="input_search" onkeyup="fetch()">';
$output .= '<button>';
$output .= 'Search';
$output .= '</button>';
$output .= '</form>';
$output .= '<div class="search_result" id="datafetch">';
$output .= '<ul>';
$output .= '<li>Please wait..</li>';
$output .= '</ul>';
$output .= '</div>';
$output .= '</div>';
return $output;
}
/**
* Ajax Search
*/
// add the ajax fetch js
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
</script>
<?php
}
And lastly, the links I’ve researched before posting here:
WP_Query with meta_value LIKE ‘something%’
How to search for meta_query LIKE or tax_query LIKE and grab these posts on search results?
Leave an answer