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?

  • 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. – Subharanjan Jul 6 '15 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. – user2994718 Jul 6 '15 at 10:56
1

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();
| improve this answer | |
  • That's fantastic! Works like a charm! – user2994718 Jul 6 '15 at 11:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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