根据产品ID

时间:2017-01-20 18:08:23

标签: php wordpress woocommerce cart product

我正在尝试将所有产品重定向到一个自定义页面除了3个去Checkout的产品(此部分有效)。

function my_custom_add_to_cart_redirect( $url ) {

        if ( ! isset( $_REQUEST['add-to-cart'] ) || ! is_numeric( $_REQUEST['add-to-cart'] ) ) {
            $url = get_permalink( 16 ); // URL page ID to redirect for all pages but below mentioned        
            return $url;
        }

        $product_id = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $_REQUEST['add-to-cart'] ) );

        // Only redirect the product IDs in the array to the checkout
        if ( in_array( $product_id, array( 999, 997, 872) ) ) {
            $url = WC()->cart->get_checkout_url();
        }

        return $url;
    }
    add_filter( 'woocommerce_add_to_cart_redirect', 'my_custom_add_to_cart_redirect' );

1 个答案:

答案 0 :(得分:2)

要使代码按预期工作,非常简单。下面我更改了你的代码:

add_filter( 'woocommerce_add_to_cart_redirect', 'my_custom_add_to_cart_redirect', 10, 1 );
function my_custom_add_to_cart_redirect( $url ) {

    $product_id = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $_REQUEST['add-to-cart'] ) );

    // Only redirect the product IDs in the array to the checkout
    if ( in_array( $product_id, array( 999, 997, 872) ) ) {
        // This is more correct to get the checkout URL
        $url = get_permalink( get_option('woocommerce_checkout_page_id') );
    } else {
        // All other products that are not in your array will be redirected to this URL
        $url = get_permalink( 16 ); // URL page ID to redirect for all pages but below mentioned
    }   
    return $url;
}

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

此代码经过测试并有效。