Woocommerce: Recently viewed cookie missing

Created on 30 Nov 2015  路  3Comments  路  Source: woocommerce/woocommerce

The woocommerce_recently_viewed cookie that gets set now only seems to set if the using woocommerce_recently_viewed_products widget.

I was using this cookie elsewhere as per this article but now it no longer works. I don't know which version this was last working in, but the cond responsible for this is in wc-product-functions:477.

Does it not make better sense to just have the cond be that the user is on a singular product?

Most helpful comment

This cookie is only used in for for the widget - for us, it's unnecessary tracking if you're not using it.

You can include your own code to track/create cookies if wanted.

function custom_track_product_view() {
    if ( ! is_singular( 'product' ) ) {
        return;
    }

    global $post;

    if ( empty( $_COOKIE['woocommerce_recently_viewed'] ) )
        $viewed_products = array();
    else
        $viewed_products = (array) explode( '|', $_COOKIE['woocommerce_recently_viewed'] );

    if ( ! in_array( $post->ID, $viewed_products ) ) {
        $viewed_products[] = $post->ID;
    }

    if ( sizeof( $viewed_products ) > 15 ) {
        array_shift( $viewed_products );
    }

    // Store for session only
    wc_setcookie( 'woocommerce_recently_viewed', implode( '|', $viewed_products ) );
}

add_action( 'template_redirect', 'custom_track_product_view', 20 );

All 3 comments

This cookie is only used in for for the widget - for us, it's unnecessary tracking if you're not using it.

You can include your own code to track/create cookies if wanted.

function custom_track_product_view() {
    if ( ! is_singular( 'product' ) ) {
        return;
    }

    global $post;

    if ( empty( $_COOKIE['woocommerce_recently_viewed'] ) )
        $viewed_products = array();
    else
        $viewed_products = (array) explode( '|', $_COOKIE['woocommerce_recently_viewed'] );

    if ( ! in_array( $post->ID, $viewed_products ) ) {
        $viewed_products[] = $post->ID;
    }

    if ( sizeof( $viewed_products ) > 15 ) {
        array_shift( $viewed_products );
    }

    // Store for session only
    wc_setcookie( 'woocommerce_recently_viewed', implode( '|', $viewed_products ) );
}

add_action( 'template_redirect', 'custom_track_product_view', 20 );

Hi @mikejolley This used to work for me, but not anymore, not sure why, but it simply doesn't add this cookie. Am I missing anything ?

Hi @mikejolley This used to work for me, but not anymore, not sure why, but it simply doesn't add this cookie. Am I missing anything ?

Just tested and works fine in WooCommerce 4.0.1.

Was this page helpful?
0 / 5 - 0 ratings