Friday, April 24, 2015

Customizing product search with meta key in wordpress woocommerce

Suppose we have a custom fields like price, color etc in woocommerce product. How we will include these fields in wordpress search? Below is the step to include these keywords in wordpress search.

Make an array like below for meta search.

$args = array(
'post_type'=>'product',
'posts_per_page' => -1,
'order' => 'ASC',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'price',               //your meta key
'value' => $_GET['price'],  //your search post value
'compare' => '='
)
)
);

Instead of =, we can use LIKE ,> or < etc.

$the_query = new WP_Query( $args ); // make query in wordpress
$q1 = $the_query->get_posts(); get all product with search.

Make an array like below to include normal search in wordpress:

$args2 = array(
'post_type'=>'product',
's' => $_GET['s'],

);


$the_query2 = new WP_Query( $args2 );
$q2 = $the_query2->get_posts(); // get all product whose title are related to the fields value.

Now merge both the result :
$merged = array_merge( $q1, $q2 );

and get the post id of all product in a array, like below :

$post_ids = array();
foreach( $merged as $item ) {
$post_ids[] = $item->ID;
}

Now get the unique id from above array.
$unique = array_unique($post_ids);

Now again make a query with these ids

$args3 = array(
'post_type'=>'product',
'post__in' => $unique,
'post_status' => 'publish',

);
$the_query3 = new WP_Query( $args3 );

Now we can use normal wordpress function to get product detail:

<?php
if ( $the_query3->have_posts() ) {
while ( $the_query3->have_posts() ) : $the_query3->the_post();
// product detail goes here.
endwhile; // end of the loop.
} // end of if
?>

2 comments: