【发布时间】:2020-07-15 22:19:53
【问题描述】:
我创建了一个最近查看的脚本,该脚本生成了一个短代码,然后我将其插入到我的主页中。
该脚本的设计是为了让那些可能访问过我的网站并离开的人在回来后可以立即看到他们上次访问时查看的产品。
我已输入简码[woocommerce_recently_viewed_products]
并使用以下脚本生成了短代码:
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();
wc_setcookie( 'woocommerce_recently_viewed', implode( '|', $viewed_products ) );
}
// Get products per page
if( !isset( $per_page ) ? $number = 4 : $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");
一切似乎都已注册。但是,当我自己测试时。我查看了一些产品,回到注册短代码的主页,我看到了文字
您还没有查看任何产品!
我不知道在注册和展示我或潜在客户可能查看过的产品时可能缺少什么。
【问题讨论】:
-
缺少设置 cookie 的代码...您可以添加它来编辑您的问题吗?
-
@LoicTheAztec 我错过了设置的 cookie。我尝试添加但得到相同的结果,我更新了问题
-
is_product()条件为真时需要设置cookie。
-
@AndrewSchultz 所以代码显示正确,只是顺序错误?我已经尝试移动 wc_setcookie() 但仍然得到相同的结果
标签: wordpress woocommerce shortcode