wordpress - 如何在 WooCommerce WordPress 5.0.3 版中显示最近查看的产品
问题描述
你能告诉我在 WooCommerce 中包含最近查看的产品的编码吗
解决方案
尝试在您要显示的位置添加以下代码段
<div>
<?php
echo do_shortcode("[woocommerce_recently_viewed_products per_page='5']");
?>
</div>
将以下代码添加到您的活动主题的functions.php
function rc_woocommerce_recently_viewed_products( $atts, $content = null ) {
// Get shortcode parameters
extract(shortcode_atts(array(
"per_page" => '5'
), $atts));
// Get WooCommerce Global
global $woocommerce;
// Get recently viewed product cookies data
$viewed_products = ! empty( $_COOKIE['woocommerce_recently_viewed'] ) ? (array) explode( '|', $_COOKIE['woocommerce_recently_viewed'] ) : array();
$viewed_products = array_filter( array_map( 'absint', $viewed_products ) );
// If no data, quit
if ( empty( $viewed_products ) )
return __( 'You have not viewed any product yet!', 'rc_wc_rvp' );
// Create the object
ob_start();
// Get products per page
if( !isset( $per_page ) ? $number = 5 : $number = $per_page )
// Create query arguments array
$query_args = array(
'posts_per_page' => $number,
'no_found_rows' => 1,
'post_status' => 'publish',
'post_type' => 'product',
'post__in' => $viewed_products,
'orderby' => 'rand'
);
// Add meta_query to query args
$query_args['meta_query'] = array();
// Check products stock status
$query_args['meta_query'][] = $woocommerce->query->stock_status_meta_query();
// Create a new query
$r = new WP_Query($query_args);
// If query return results
if ( $r->have_posts() ) {
$content = '<ul class="rc_wc_rvp_product_list_widget">';
// Start the loop
while ( $r->have_posts()) {
$r->the_post();
global $product;
$content .= '<li>
<a href="' . get_permalink() . '">
' . ( has_post_thumbnail() ? get_the_post_thumbnail( $r->post->ID, 'shop_thumbnail' ) : woocommerce_placeholder_img( 'shop_thumbnail' ) ) . ' ' . get_the_title() . '
</a> ' . $product->get_price_html() . '
</li>';
}
$content .= '</ul>';
}
// Get clean object
$content .= ob_get_clean();
// Return whole content
return $content;
}
// Register the shortcode
add_shortcode("woocommerce_recently_viewed_products", "rc_woocommerce_recently_viewed_products");
推荐阅读
- typescript - 如何在 Typescript 中定义数组的数量
- javascript - 在 jQuery 中引导表单验证而不是纯 JavaScript?
- java - 从数组中分离素数
- python - 在 Python 中将 2D 列表转换为 3D 列表
- android - 自定义维度 - 何时发送用户范围自定义维度
- php - 向 Symfony Flex 项目添加配置
- javascript - 计算 Angular 6 检查了多少个复选框
- java - 检查特定端口在 Solaris 中是否空闲
- ckeditor - CKEditor 中的 TAB
- c# - ASP.NET 根据 ViewState 中的值加载动态控件