Skip to content

Instantly share code, notes, and snippets.

@santanup789
Created May 19, 2021 11:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save santanup789/819a95988336f76fa9a15a18e4e49f2c to your computer and use it in GitHub Desktop.
Save santanup789/819a95988336f76fa9a15a18e4e49f2c to your computer and use it in GitHub Desktop.
Woocommerce AJAX product search [excluded catalog hidden products]
add_action('wp_footer', 'ajax_product_fetch');
function ajax_product_fetch()
{
?>
<script type="text/javascript">
function product_fetch() {
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: {action: 'product_fetch', product_keyword: jQuery('#product_keyword').val()},
success: function (data) {
jQuery('#productfetch').html(data).show();
if (data.trim() == '') {
jQuery('#productfetch').html('Nothing found...');
}
}
});
}
</script>
<?php
}
// the ajax function
add_action('wp_ajax_product_fetch', 'product_fetch');
add_action('wp_ajax_nopriv_product_fetch', 'product_fetch');
function product_fetch()
{
// $the_queryx = new WP_Query(
// [
// 'posts_per_page' => -1,
// 's' => esc_attr($_POST['product_keyword']),
// 'post_type' => 'product',
// ]
// );
$args = array (
'post_type' => 'product',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'exclude-from-catalog',
'operator' => 'NOT IN',
),
),
);
$the_queryx = new WP_Query( $args );
if ($the_queryx->have_posts()) :
while ($the_queryx->have_posts()): $the_queryx->the_post();
$myqueryx = esc_attr($_POST['product_keyword']);
$ax = $myqueryx;
$searchx = get_the_title();
$postURL = get_permalink();
if (stripos("/{$searchx}/", $ax) !== false) { ?>
<div>
<?php echo '<a href="'.$postURL.'"><span>'.get_the_title().'</span></a>'; ?>
<?php echo "</div>"; ?>
<?php
}
endwhile;
wp_reset_postdata();
endif;
die();
}
<div class='search_news_bar'>
<input type="text" name="product_keyword" id="product_keyword" onkeyup="product_fetch()" placeholder="Search by keyword or title"></input>
<div id="productfetch"></div>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment