【问题标题】:Skip cart page for a few products redirecting to checkout跳过购物车页面,了解一些重定向到结账的产品
【发布时间】:2017-03-28 08:31:46
【问题描述】:

我想绕过购物车页面并将用户重定向到一些产​​品的结帐页面。

我已经为产品创建了添加到购物车的链接 <a href="http://example.net/?add-to-cart=1461">Product Name</a>

我有下面的代码

add_filter( 'woocommerce_add_to_cart_redirect', 'woo_redirect_checkout' );

function woo_redirect_checkout() {
    global $woocommerce;
    $desire_product = 1461;
    //Get product ID
    $product_id = (int) apply_filters( 'woocommerce_add_to_cart_product_id', $_POST['add-to-cart'] );

    //Check if current product is subscription
    if ( $product_id == $desire_product ){
        $checkout_url = $woocommerce->cart->get_checkout_url();
        return $checkout_url;
        exit;
    } else {
        $cart_url = $woocommerce->cart->get_cart_url();
        return $cart_url;
        exit;
    }
}

来自How to skip cart page on woocomerce for certain products only?。但网址将我重定向到主页。只是想知道问题出在哪里,

我也在 woocommerce 设置中取消选中添加到购物车的行为。

提前致谢。

【问题讨论】:

    标签: php wordpress woocommerce cart product


    【解决方案1】:

    我选择了另一种方法和 WordPress 钩子而不是 woocommerce。这是基于这个答案:WooCommerce - Skip cart page redirecting to checkout page

    这是代码:

     function skip_cart_page_redirection_to_checkout() {
    
        // desired product id redirection
        $product_id = 1461;
        $items_ids = array();
    
        // Get all items IDs that are in cart
        foreach( WC()->cart->get_cart() as $item ) {
            $items_ids[] = $item['product_id'];
        }
    
        // If is cart page and the desired peoduct is in cart => redirect to checkout.
        if( is_cart() && in_array($product_id, $items_ids) )
            // WooCommerce 3.0 compatibility added
            if ( version_compare( WC_VERSION, '2.7', '<' ) ) {
                wp_redirect( WC()->cart->get_checkout_url() ); // Older than 3.0
            } else {
                wp_redirect( wc_get_checkout_url() ); // 3.0+ (Thanks to helgatheviking)
            }
    
    }
    add_action('template_redirect', 'skip_cart_page_redirection_to_checkout');
    

    此代码在您的活动子主题(或主题)的 function.php 文件中或任何插件文件中。

    代码已经过测试并且功能齐全。

    【讨论】:

    • 源评论说get_checkout_url() 已被弃用,但它实际上并没有被弃用。无论如何,source 建议使用wc_get_checkout_url()
    • @helgatheviking 哦,谢谢,所有版本都更新了……我知道,我的很多答案现在与 woocommerce 3.0+ 不兼容……我会尝试逐步更新它们……
    • 消息来源说 wc_get_checkout_url() 从 2.5 开始可用。 :shrugs: :) 这并不能否定你所说的关于现在已经过时的答案。不过我不会太担心。你发帖时他们是对的。
    猜你喜欢
    • 2014-08-30
    • 2018-03-31
    • 1970-01-01
    • 2018-07-11
    • 2016-01-02
    • 2016-09-29
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    相关资源
    最近更新 更多