我在点击产品页面上的“添加到购物车”时,尝试将用户重定向到上一个类别页面。但是在重定向上,我看到了一个空白的product_cat属性。即example.com/?product_cat=
但是,如果我将其回显到woocommerce_product_thumbnail
,它会完美地显示链接。即example.com/?product_cat=shoes
add_filter ('add_to_cart_redirect', 'redirect_to_previousCat');
//add_filter ('woocommerce_product_thumbnails', 'redirect_to_previousCat');
function redirect_to_previousCat() {
global $woocommerce, $post;
$product_cat_slug;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
$product_cat_slug = $term->slug;
break;
}
$url=get_site_url().'?product_cat='.$product_cat_slug;
return $url;
}
答案 0 :(得分:3)
正如我在评论中提到的,当$post
方法在add_to_cart_action()
挂钩上运行时,尚未设置全局init
。
相反,我建议您关注Wootheme的主管并从$_REQUEST
全球范围获取产品ID。
add_filter ('add_to_cart_redirect', 'redirect_to_previousCat');
function redirect_to_previousCat( $url ) {
$product_id = absint( $_REQUEST['add-to-cart'] );
$product_cat_slug = '';
$terms = get_the_terms( $product_id, 'product_cat' );
foreach ( $terms as $term ) {
$product_cat_slug = $term->slug;
break;
}
if( $product_cat_slug ){
$url = add_query_arg( 'product_cat', $product_cat_slug, site_url() );
}
return $url;
}