Skip to content

Instantly share code, notes, and snippets.

@ibndawood
Created September 17, 2015 12:49
Show Gist options
  • Save ibndawood/dc7b386d9e890af153e3 to your computer and use it in GitHub Desktop.
Save ibndawood/dc7b386d9e890af153e3 to your computer and use it in GitHub Desktop.
Removing Out of Stock items in Live Search
function woocommerce_products_live_search(){
if ( isset( $_REQUEST['fn'] ) && 'get_ajax_search' == $_REQUEST['fn'] ) {
$query_args = array(
'posts_per_page' => 10,
'no_found_rows' => true,
'post_type' => 'product',
);
if( isset( $_REQUEST['terms'] ) ) {
$query_args['s'] = $_REQUEST['terms'];
}
$search_query = new WP_Query( $query_args );
$results = array( );
if ( $search_query->get_posts() ) {
foreach ( $search_query->get_posts() as $the_post ) {
$title = get_the_title( $the_post->ID );
if ( has_post_thumbnail( $the_post->ID ) ) {
$post_thumbnail_ID = get_post_thumbnail_id( $the_post->ID );
$post_thumbnail_src = wp_get_attachment_image_src( $post_thumbnail_ID, 'thumbnail' );
}else{
$dimensions = wc_get_image_size( 'thumbnail' );
$post_thumbnail_src = array(
wc_placeholder_img_src(),
esc_attr( $dimensions['width'] ),
esc_attr( $dimensions['height'] )
);
}
$product = new WC_Product( $the_post->ID );
$price = $product->get_price_html();
$brand = woocommerce_show_brand( $the_post->ID, true );
$title = html_entity_decode( $title , ENT_QUOTES, 'UTF-8' );
if( $product->is_in_stock() ) {
$results[] = array(
'value' => $title,
'url' => get_permalink( $the_post->ID ),
'tokens' => explode( ' ', $title ),
'image' => $post_thumbnail_src[0],
'price' => $price,
'brand' => $brand,
'id' => $the_post->ID
);
}
}
}
wp_reset_postdata();
echo json_encode( $results );
}
die();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment