php - 在 Woocommerce 中购买某个产品类别的产品时重定向

标签 php wordpress woocommerce cart custom-taxonomy

我有这个代码:

add_action('template_redirect', 'woo_custom_redirect');
function woo_custom_redirect( $redirect ) {

if (
    ! is_user_logged_in()       
    && (is_checkout())
    ) {
    wp_redirect( home_url( '/my-account/edit-account/' ) );
    return $redirect;
    }
}

如何在下单购买某个类别的产品时替换重定向条件?

例如,如果用户购买了某个类别的产品,那么当他尝试下订单时,他会重定向到注册并在注册成功后返回。

最佳答案

当非登录用户拥有特定产品类别的商品时,以下代码会将未登录用户重定向到我的帐户页面。您必须在代码中定义您的特定产品类别:

add_action('template_redirect', 'woo_custom_redirect');
function woo_custom_redirect( $redirect ) {
    // HERE set your product category (can be term IDs, slugs or names)
    $category = 'posters';

    $found = false;

    // CHECK CART ITEMS: search for items from our product category
    foreach ( WC()->cart->get_cart() as $cart_item ){
        if( has_term( $category, 'product_cat', $cart_item['product_id'] ) ) {
            $found = true; 
            break;
        }
    }

    if ( ! is_user_logged_in() && is_checkout() && $found ) {
        wp_redirect( get_permalink( get_option('woocommerce_myaccount_page_id') ) );
        exit();
    }
}

代码进入事件子主题(或事件主题)的 function.php 文件。经过测试并有效。

关于php - 在 Woocommerce 中购买某个产品类别的产品时重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51941923/

相关文章:

php - 禁用(删除)WooCommerce 4.3.x 中的营销菜单选项

php - 移除模块并连接一个新模块

php - 使用 Jquery 增加 HTML 值并将输入数据提交给 PHP

php - 从 wordpress 图像中删除日期?

php - Woocommerce 设置运输方式,获取运费

php - 使用 CSS/Woocommerce/Wordpress 定位特定字段框名称

php - 用户名可用性检查未连接

wordpress - 更改 WordPress TinyMCE 编辑器中的短代码外观

html - 如何将div分开显示在同一行?

wordpress - 如何在 WooCommerce 上强制更新购物车(不改变数量)