当用户单击产品页面上的“添加到购物车”时,我试图将其重定向到上一个类别页面。但在重定向上,我看到一个空白的product_cat属性。i、 e.示例。com/?product_cat=
但是,如果我将其回显到woocommerce\u product_缩略图
中,它会完美地显示链接。i、 e.示例。com/?产品类别=鞋子
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;
}
正如我在评论中提到的,当add_to_cart_action()
方法在init
钩子上运行时,还没有设置全局$post
。
相反,我建议您遵循Wootheme的指导,从$\u请求
全局获取产品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;
}