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.
Opens WPIDE on
Code
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 add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.