当前位置:首页>>WordPress教程

WordPress Woocommerce Recently Viewed Products 查看最近浏览过的产品

add_shortcode( 'recently_viewed_products', 'bbloomer_recently_viewed_shortcode' );function bbloomer_recently_viewed_shortcode() { $viewed_products = ! empty( $_COOKIE['woocommerce_recently_viewed'] ) ? (array) explode( '|', wp_unslash( $_COOKIE['woocom

admin

add_shortcode( 'recently_viewed_products', 'bbloomer_recently_viewed_shortcode' );

function bbloomer_recently_viewed_shortcode() {

   $viewed_products = ! empty( $_COOKIE['woocommerce_recently_viewed'] ) ? (array) explode( '|', wp_unslash( $_COOKIE['woocommerce_recently_viewed'] ) ) : array();

   $viewed_products = array_reverse( array_filter( array_map( 'absint', $viewed_products ) ) );

 $viewed_products = array_slice($viewed_products, 0, 4);

   if ( empty( $viewed_products ) ) return;

   $title = '<h3>Recently Viewed Products</h3>';

   $product_ids = implode( ",", $viewed_products );

   return $title . do_shortcode("[products ids='$product_ids']");

}

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 );

之后使用[recently_viewed_products]调用

其中 $viewed_products = array_slice($viewed_products, 0, 4);为显示4条产品。

以上代码也可解决WordPress Woocommerce Recently Viewed Products 显示空白无法显示产品的问题。

最后,还是建议使用专业插件来实现更多Recently Viewed Products的自定义功能。比如显示的顺序、显示的类别、显示所有浏览的产品记录、设置滑块效果等。


{dede:include filename="menu.htm"/}