0

I'm trying to retrieve data set in a cookie and use this to run a query.

I've set the cookie in functions.php like so;

add_action( 'init', 'resultsCookie' );
function resultsCookie() {

   setcookie( 'your-results', '18,17,11,8,10,27,26', time() + 3600, COOKIEPATH, COOKIE_DOMAIN );
}

While I can echo the string, I can't seem to get this functioning within the query;

$cookie_array = $_COOKIE["your-results"];

// Test output              
echo $cookie_array;

$sug_args =  array(
  'post_type' => 'product',
  'post__in' => array( $cookie_array )
);

$sug_query = new WP_query ($sug_args);

if($sug_query->have_posts()) : while($sug_query->have_posts()) : $sug_query->the_post();

  // Run Loop                   
  wc_get_template_part( 'content', 'product' ); 

endwhile; endif; wp_reset_query();

Any ideas?

2
  • What kind of data type is there in $_COOKIE["your-results"] ? If this is an array, you don't need to wrap this within array( $cookie_array ). Try (array) $cookie_array; instead. Commented Jul 6, 2015 at 10:52
  • Just a string '18,17,11,8,10,27,26'. Strangely, it seems to pick out the first id just fine; for example '18'. However, the suggested tweak doesn't help unfortunately. Commented Jul 6, 2015 at 10:56

1 Answer 1

2

You need to explode the comma separated string to get the array of IDs. Follow the below code.

$cookie_array = $_COOKIE["your-results"];

// Test output              
echo $cookie_array;

$cookie_array = array_map( 'absint', (array) explode(',', $cookie_array) );

$sug_args =  array(
  'post_type' => 'product',
  'post__in'  => $cookie_array,
);

$sug_query = new WP_query ($sug_args);

if( $sug_query->have_posts() ) : 
    while( $sug_query->have_posts() ) : 
        $sug_query->the_post();

        // Run Loop                   
        wc_get_template_part( 'content', 'product' ); 

    endwhile; 
endif; 

wp_reset_query();
2
  • That's fantastic! Works like a charm! Commented Jul 6, 2015 at 11:11
  • Great, Worked like a charm, Thank you so much :)
    – Jodyshop
    Commented Nov 28, 2020 at 4:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.