Similar to what you see on stores like Etsy, I would like to display the number of people that have a product in their cart.
Via Show how many people have added a product in their current cart, I was able to achieve it.
But my website is still under construction, and when I start it, I would like to make it look like 2-4 people already have the product in their cart.
So I made an adjustment to that existing code, I added $in_basket = rand(2, 4); which gives as complete result:
function show_no_of_people_added_in_cart() {
global $wpdb, $product;
$in_basket = rand(2, 4);
$wc_session_data = $wpdb->get_results( "SELECT session_key FROM {$wpdb->prefix}woocommerce_sessions" );
$wc_session_keys = wp_list_pluck( $wc_session_data, 'session_key' );
if ( $wc_session_keys ) {
foreach ( $wc_session_keys as $key => $_customer_id ) {
// if you want to skip current viewer cart item in counts or else can remove belows checking
if( WC()->session->get_customer_id() == $_customer_id ) continue;
$session_contents = WC()->session->get_session( $_customer_id, array() );
$cart_contents = maybe_unserialize( $session_contents['cart'] );
if ( $cart_contents ) {
foreach ( $cart_contents as $cart_key => $item ) {
if( $item['product_id'] == $product->get_id() ) {
$in_basket += 1;
}
}
}
}
}
if ( $in_basket )
echo '<div class="in-basket">' . sprintf( __( 'Hurry! %d people have this in their cart!', 'text-domain' ), $in_basket ) . '</div>';
}
add_action( 'woocommerce_after_shop_loop_item_title', 'show_no_of_people_added_in_cart', 11 );
add_action( 'woocommerce_single_product_summary', 'show_no_of_people_added_in_cart', 21 );
But the problem with is that at every refresh the number changes. How can I keep that random number for a while? Any advice?