# Recently Viewed Products Shortcode

> Remembers the products each visitor looks at and adds a [wpide_recently_viewed] shortcode that displays them as a product grid.

- Type: PHP
- Runs: Run everywhere
- Category: [WooCommerce](https://wpide.com/library/category/woocommerce/)
- Requires: WooCommerce
- Tags: woocommerce, shortcode, products, personalization
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/woo-recently-viewed-shortcode/

## Code

```php
add_action( 'template_redirect', function () {
    if ( ! function_exists( 'is_product' ) || ! is_product() || headers_sent() ) {
        return;
    }

    $id     = (int) get_queried_object_id();
    $viewed = isset( $_COOKIE['wpide_viewed'] ) ? wp_parse_id_list( wp_unslash( $_COOKIE['wpide_viewed'] ) ) : array();
    $viewed = array_diff( $viewed, array( $id ) );
    array_unshift( $viewed, $id );
    $viewed = array_slice( $viewed, 0, 15 );

    setcookie( 'wpide_viewed', implode( ',', $viewed ), array(
        'expires'  => time() + 30 * DAY_IN_SECONDS,
        'path'     => COOKIEPATH ? COOKIEPATH : '/',
        'domain'   => COOKIE_DOMAIN,
        'secure'   => is_ssl(),
        'httponly' => true,
        'samesite' => 'Lax',
    ) );
}, 20 );

add_shortcode( 'wpide_recently_viewed', function ( $atts ) {
    $atts   = shortcode_atts( array( 'limit' => 4, 'columns' => 4 ), $atts, 'wpide_recently_viewed' );
    $viewed = isset( $_COOKIE['wpide_viewed'] ) ? wp_parse_id_list( wp_unslash( $_COOKIE['wpide_viewed'] ) ) : array();

    if ( is_product() ) {
        $viewed = array_diff( $viewed, array( (int) get_queried_object_id() ) );
    }

    $viewed = array_slice( $viewed, 0, absint( $atts['limit'] ) );

    if ( ! $viewed ) {
        return '';
    }

    return do_shortcode( sprintf( '[products ids="%1$s" orderby="post__in" columns="%2$d"]', esc_attr( implode( ',', $viewed ) ), absint( $atts['columns'] ) ) );
} );
```

## Notes

Products are stored in a first-party cookie for 30 days. Use [wpide_recently_viewed limit="4"] to change how many are shown.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Recently Viewed Products Shortcode" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
