将产品添加到购物车后清理/重定向 URL

发布于 2025-01-12 11:29:10 字数 4873 浏览 1 评论 0原文

自从 elementor 和 woocommerce 最新版本发布以来,我似乎遇到了一个无法解决的问题。

基本上,我通过使用来自表单计算器的数据进行 url 操作,将多个产品添加到购物车。这种方法在一年多的时间里运作良好,但现在突然失效了。

1.功能描述

当我按下计算器页面上的按钮时,它会计算值,然后将其解析到字段中并添加到当前网址。

document.location.href='?add-to-cart=' +fieldname51+':'+fieldname15+',' +fieldname52+':'+fieldname16+',' +fieldname53+':'+fieldname17+',' , . ...

该字段的数据示例,其中适用以下内容::,:<产品数量2> , ...

?add-to-cart=11439:4,0:0,0:0,0:0,0:0,11469:2,0:0,0:0,0:0,5213:1,11425:1,5246:1,5275:2,5304:2,5329:6,0:0,0:0,0:0,0:0,0:0,0:0,0:0,0:0,0:0,0:0,11705:6 

我使用并修改了一些代码片段,通过 woocommerce 中的 url 将多个产品变体添加到购物车,并将其添加到 WordPress 中的functions.php 文件中:


/** ADD PRODUCTS THROUGH URL CODE **/


function webroom_add_multiple_products_to_cart( $url = false ) {
    // Make sure WC is installed, and add-to-cart qauery arg exists, and contains at least one comma.
    if ( ! class_exists( 'WC_Form_Handler' ) || empty( $_REQUEST['add-to-cart'] ) || false === strpos( $_REQUEST['add-to-cart'], ',' ) ) {
        return;
    }

    // Remove WooCommerce's hook, as it's useless (doesn't handle multiple products).
    remove_action( 'wp_loaded', array( 'WC_Form_Handler', 'add_to_cart_action' ), 20 );

    $product_ids = explode( ',', $_REQUEST['add-to-cart'] );
    $count       = count( $product_ids );
    $number      = 0;

    foreach ( $product_ids as $id_and_quantity ) {
        // Check for quantities defined in curie notation (<product_id>:<product_quantity>)
        
        $id_and_quantity = explode( ':', $id_and_quantity );
        $product_id = $id_and_quantity[0];

        $_REQUEST['quantity'] = ! empty( $id_and_quantity[1] ) ? absint( $id_and_quantity[1] ) : 1;

        if ( ++$number === $count ) {
            // Ok, final item, let's send it back to woocommerce's add_to_cart_action method for handling.
            $_REQUEST['add-to-cart'] = $product_id;

            return WC_Form_Handler::add_to_cart_action( $url );
        }

        $product_id        = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $product_id ) );
        $was_added_to_cart = false;
        $adding_to_cart    = wc_get_product( $product_id );

        if ( ! $adding_to_cart ) {
            continue;
        }

        $add_to_cart_handler = apply_filters( 'woocommerce_add_to_cart_handler', $adding_to_cart->get_type(), $adding_to_cart );

        // Variable product handling
        if ( 'variable' === $add_to_cart_handler ) {
            woo_hack_invoke_private_method( 'WC_Form_Handler', 'add_to_cart_handler_variable', $product_id );

        // Grouped Products
        } elseif ( 'grouped' === $add_to_cart_handler ) {
            woo_hack_invoke_private_method( 'WC_Form_Handler', 'add_to_cart_handler_grouped', $product_id );

        // Custom Handler
        } elseif ( has_action( 'woocommerce_add_to_cart_handler_' . $add_to_cart_handler ) ){
            do_action( 'woocommerce_add_to_cart_handler_' . $add_to_cart_handler, $url );

        // Simple Products
        } else {
            woo_hack_invoke_private_method( 'WC_Form_Handler', 'add_to_cart_handler_simple', $product_id );
        }
    }
}

// Fire before the WC_Form_Handler::add_to_cart_action callback.
add_action( 'wp_loaded', 'webroom_add_multiple_products_to_cart', 15 );


/**
 * Invoke class private method
 *
 * @since   0.1.0
 *
 * @param   string $class_name
 * @param   string $methodName
 *
 * @return  mixed
 */
function woo_hack_invoke_private_method( $class_name, $methodName ) {
    if ( version_compare( phpversion(), '5.3', '<' ) ) {
        throw new Exception( 'PHP version does not support ReflectionClass::setAccessible()', __LINE__ );
    }

    $args = func_get_args();
    unset( $args[0], $args[1] );
    $reflection = new ReflectionClass( $class_name );
    $method = $reflection->getMethod( $methodName );
    $method->setAccessible( true );

    //$args = array_merge( array( $class_name ), $args );
    $args = array_merge( array( $reflection ), $args );
    return call_user_func_array( array( $method, 'invoke' ), $args );
    
}


2。问题

现在,由于某种原因,当按下计算按钮时,它确实按预期执行并将所述产品添加到购物车,但是字段参数仍然停留在网址中

发生的情况是,一旦您按下网站上的另一个链接、购物车或其他任何内容,它就会“刷新”页面并再次解析相同的字段值,导致购物车中的产品数量是预期的两倍< /强>。

3.尝试了以下方法

我尝试使用window.location.replace计算后重定向字段数据,但它在有时间计算并将产品添加到购物车

setTimeout( function(){window.location.replace("url or url/fielddata");},3000); 当从计算按钮添加到 onclick 事件时也不起作用,因为这样它就不再看到该字段数据或进行计算,在购物车中不添加任何内容,

尝试在单击失败后“删除参数”并导致与上述相同的问题。

4。目标

目标是在按下按钮并将产品添加到购物车后清理 URL,或者重定向到购物篮或任何自定义 URL,而无需再次解析字段数据中的现有参数。任何一种解决方案都可以,但也许不可能做到。

Since the latest releases of elementor and woocommerce i seem to be having a problem i cant fix.

Basically im adding multiple products to cart by url manipulation with data coming from a form calculator. This worked well for over a year and now suddenly doesnt.

1. Description of the function

When i press the button on the calculator page, it calculates the values which are then parsed into a field and added to the current url.

document.location.href='?add-to-cart=' +fieldname51+':'+fieldname15+',' +fieldname52+':'+fieldname16+',' +fieldname53+':'+fieldname17+',' , ....

example of the data of such field where following applies: <productid1>:<product quantitiy1> , <productid2>:<product quantitiy2> , ...

?add-to-cart=11439:4,0:0,0:0,0:0,0:0,11469:2,0:0,0:0,0:0,5213:1,11425:1,5246:1,5275:2,5304:2,5329:6,0:0,0:0,0:0,0:0,0:0,0:0,0:0,0:0,0:0,0:0,11705:6 

I've used and adapted some code snippets to add multiple product variations to cart through url in woocommerce and added it to my functions.php file in wordpress:


/** ADD PRODUCTS THROUGH URL CODE **/


function webroom_add_multiple_products_to_cart( $url = false ) {
    // Make sure WC is installed, and add-to-cart qauery arg exists, and contains at least one comma.
    if ( ! class_exists( 'WC_Form_Handler' ) || empty( $_REQUEST['add-to-cart'] ) || false === strpos( $_REQUEST['add-to-cart'], ',' ) ) {
        return;
    }

    // Remove WooCommerce's hook, as it's useless (doesn't handle multiple products).
    remove_action( 'wp_loaded', array( 'WC_Form_Handler', 'add_to_cart_action' ), 20 );

    $product_ids = explode( ',', $_REQUEST['add-to-cart'] );
    $count       = count( $product_ids );
    $number      = 0;

    foreach ( $product_ids as $id_and_quantity ) {
        // Check for quantities defined in curie notation (<product_id>:<product_quantity>)
        
        $id_and_quantity = explode( ':', $id_and_quantity );
        $product_id = $id_and_quantity[0];

        $_REQUEST['quantity'] = ! empty( $id_and_quantity[1] ) ? absint( $id_and_quantity[1] ) : 1;

        if ( ++$number === $count ) {
            // Ok, final item, let's send it back to woocommerce's add_to_cart_action method for handling.
            $_REQUEST['add-to-cart'] = $product_id;

            return WC_Form_Handler::add_to_cart_action( $url );
        }

        $product_id        = apply_filters( 'woocommerce_add_to_cart_product_id', absint( $product_id ) );
        $was_added_to_cart = false;
        $adding_to_cart    = wc_get_product( $product_id );

        if ( ! $adding_to_cart ) {
            continue;
        }

        $add_to_cart_handler = apply_filters( 'woocommerce_add_to_cart_handler', $adding_to_cart->get_type(), $adding_to_cart );

        // Variable product handling
        if ( 'variable' === $add_to_cart_handler ) {
            woo_hack_invoke_private_method( 'WC_Form_Handler', 'add_to_cart_handler_variable', $product_id );

        // Grouped Products
        } elseif ( 'grouped' === $add_to_cart_handler ) {
            woo_hack_invoke_private_method( 'WC_Form_Handler', 'add_to_cart_handler_grouped', $product_id );

        // Custom Handler
        } elseif ( has_action( 'woocommerce_add_to_cart_handler_' . $add_to_cart_handler ) ){
            do_action( 'woocommerce_add_to_cart_handler_' . $add_to_cart_handler, $url );

        // Simple Products
        } else {
            woo_hack_invoke_private_method( 'WC_Form_Handler', 'add_to_cart_handler_simple', $product_id );
        }
    }
}

// Fire before the WC_Form_Handler::add_to_cart_action callback.
add_action( 'wp_loaded', 'webroom_add_multiple_products_to_cart', 15 );


/**
 * Invoke class private method
 *
 * @since   0.1.0
 *
 * @param   string $class_name
 * @param   string $methodName
 *
 * @return  mixed
 */
function woo_hack_invoke_private_method( $class_name, $methodName ) {
    if ( version_compare( phpversion(), '5.3', '<' ) ) {
        throw new Exception( 'PHP version does not support ReflectionClass::setAccessible()', __LINE__ );
    }

    $args = func_get_args();
    unset( $args[0], $args[1] );
    $reflection = new ReflectionClass( $class_name );
    $method = $reflection->getMethod( $methodName );
    $method->setAccessible( true );

    //$args = array_merge( array( $class_name ), $args );
    $args = array_merge( array( $reflection ), $args );
    return call_user_func_array( array( $method, 'invoke' ), $args );
    
}


2. The problem

Now for some reason when pressing the calculation button, it indeed does as expected and adds said products to cart, however the field parameters stay stuck in the url.

What happens is as soon as you press another link on the website, or the cart or whatever, it "refreshes" the page and parses the same field values again, causing the cart to have twice the amount of products than intended.

3. Tried the following

i've tried redirecting the field data after calculation with window.location.replace but it redirects before it has time to calculate and add the products to cart

setTimeout(function(){window.location.replace("url or url/fielddata");},3000); also didnt work when added to an onclick event from the calculation button, because then it no longer sees the field data or makes the calculations, adding nothing to cart

attempts to "remove the parametes" after clicking failed and caused the same issues as above.

4. Goal

The goal is either to clean the URL after pressing the button and adding products to cart or to redirect to the basket or any custom URL without parsing the existing parameters from the field data again. either solution would work but maybe it is not possible to do.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文