Skip to content

Instantly share code, notes, and snippets.

@farookibrahim
Created December 8, 2017 07:32
Show Gist options
  • Save farookibrahim/aab8af5b4c2c1d106a01409d9bc420fc to your computer and use it in GitHub Desktop.
Save farookibrahim/aab8af5b4c2c1d106a01409d9bc420fc to your computer and use it in GitHub Desktop.
Electro - Add recently viewed products before footer
/**
* Track product views.
*/
if( ! function_exists( 'electro_wc_track_product_view' ) ) {
function electro_wc_track_product_view() {
if ( ! is_singular( 'product' ) ) {
return;
}
global $post;
if ( empty( $_COOKIE['electro_wc_recently_viewed'] ) ) {
$viewed_products = array();
} else {
$viewed_products = (array) explode( '|', $_COOKIE['electro_wc_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( 'electro_wc_recently_viewed', implode( '|', $viewed_products ) );
}
}
add_action( 'template_redirect', 'electro_wc_track_product_view', 20 );
if( ! function_exists( 'electro_before_footer_products_recently_viewed' ) ) {
function electro_before_footer_products_recently_viewed() {
$viewed_products = ! empty( $_COOKIE['electro_wc_recently_viewed'] ) ? (array) explode( '|', $_COOKIE['electro_wc_recently_viewed'] ) : array();
$viewed_products = array_reverse( array_filter( array_map( 'absint', $viewed_products ) ) );
if ( empty( $viewed_products ) ) {
return;
}
$ids = implode( ',', $viewed_products );
?>
<section class="products-recently-viewed">
<div class="container">
<header>
<h2 class="h1"><?php echo esc_html__( 'Recently Viewed Products', 'electro' ); ?></h2>
</header>
<?php echo do_shortcode( '[products columns=4 limit=8 ids='.$ids.']' ); ?>
</div>
</section>
<?php
}
}
add_action( 'electro_before_footer', 'electro_before_footer_products_recently_viewed', 10 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment