WooCommerce 在添加到购物车时重定向到产品类别
WooCommerce redirect to product category on add to cart
当用户点击产品页面上的“添加到购物车”时,我试图将用户重定向到上一个类别页面。但是在重定向时我看到一个空白的 product_cat 属性。即 example.com/?product_cat=
但是,如果我将它回显到 woocommerce_product_thumbnail
,它会完美地显示 link。即 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;
}
正如我在评论中提到的,当 add_to_cart_action()
方法在 init
挂钩上运行时,全局 $post
尚未设置。
相反,我建议您效仿 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;
}
当用户点击产品页面上的“添加到购物车”时,我试图将用户重定向到上一个类别页面。但是在重定向时我看到一个空白的 product_cat 属性。即 example.com/?product_cat=
但是,如果我将它回显到 woocommerce_product_thumbnail
,它会完美地显示 link。即 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;
}
正如我在评论中提到的,当 add_to_cart_action()
方法在 init
挂钩上运行时,全局 $post
尚未设置。
相反,我建议您效仿 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;
}