Support

Account

Home Forums General Issues Use a JS array to search through meta_query

Solving

Use a JS array to search through meta_query

  • Hi guys!

    So I have an AJAX request that is supposed to pick up data from a couple of checkboxes and then filter the search based on which ones are selected.

    For my JS, I have this segment to get the checkboxes:

    products = new Array();
    	$('input#products:checked').each(function() {
    		products.push($(this).val());
    	});

    And in my functions.php, I have this:

    function product_search() {
    	$products = $_POST['products'];
    	
    	$args = array(
    		'posts_per_page'	=> -1,
    		'post_type'				=> 'products',
    		'meta_query'	=> array(
    			array(
    				'key'		=> 'products',
    				'value'		=> $products,
    				'compare'	=> 'IN'
    			),
    		)
    	);
    
    	// [...]
    }

    Now, if I change $products to something static, I get my results, but the array that’s being parsed from my JS doesn’t play well here. I’ve tried to used json_decode() on $products, without any good results.

    If I console log the products var, I can get this if I have two checkboxes checked:

    ["Wooden", "Plastic"]

    How can I make these guy come along?

    Thanks in advance!

  • Hi @stroperik

    What about if you do an error_log(print_r($products, true)); right after fetching the $_POST?

    Also, what kind of field is products in ACF? If it’s an checkbox field or radio the values would be saved as an serialized array and then I don’t think IN would work as comparison.

  • Hi @jonathan and thanks for the reply!

    I get this from the log:

    Array
    (
        [0] => Wooden
        [1] => Plastic
    )

    And yes, products is a checkbox field. So what is supported if I want to do a WP_Query here? My goal in the end is to combine a search field with four different columns, each with checkboxes in them and making the relation to be AND.

  • No problem 🙂

    I’m not an SQL expert but I thiiiiink you can’t do a IN search with the checkbox field as the value in the DB will be a serialized array.

    I’m not sure how well this will play with your entire solution (and it’s not really performance-effective in the long run) but try if this works.

    
    function product_search() {
    	$products = $_POST['products'];
    	
    	$args = array(
    		'posts_per_page'	=> -1,
    		'post_type'				=> 'products',
    	);
    	
    	$meta_query = array();
    	foreach( $products as $product ){
    		$meta_query[] = array(
    			'key'		=> 'products',
    			'value'		=> $product,
    			'compare'	=> 'LIKE'
    		),
    		
    	}
    	
    	$args['meta_query'] = $meta_query;
    	
    }
    
Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘Use a JS array to search through meta_query’ is closed to new replies.