结帐后以编程方式添加运输方式 - WooCommerce

Add shipping method programatically after checkout - WooCommerce

我正在尝试在结帐完成后立即插入送货方式。不幸的是,这不是很好,我不确定为什么。我在结帐后尝试了所有的挂钩,但是...

这是我的代码:

add_action('woocommerce_checkout_create_order', 'action_checkout_order_processed', 10, 1);
function action_checkout_order_processed( $order ) {

    $item = new WC_Order_Item_Shipping();

    $item->set_method_title( "Безплатна Доставка - Speedy" );
    $item->set_method_id( "speedy_shipping_method" ); // set an existing Shipping method rate ID
    $item->calculate_taxes("0");

    $shipping_item_id = $order->add_item( $item );

    wc_add_order_item_meta($shipping_item_id, "method_id", "speedy_shipping_method");
    wc_add_order_item_meta($shipping_item_id, "instance_id", "0");
    wc_add_order_item_meta($shipping_item_id, "cost", "0");
    wc_add_order_item_meta($shipping_item_id, "total_tax", maybe_unserialize('a:1:{s:5:"total";a:0:{}}'));

    $order->calculate_totals();

    $order->update_status('on-hold');

    $order->save();

}

这是另一个函数中的工作代码,所以我一定是出了什么问题,但不确定是什么。

如果有人能给我提示,在此先感谢!

您需要提高 add_action 的优先级。

add_action('woocommerce_checkout_create_order', 'action_checkout_order_processed', 10, 1);

更多详情请看下面link.

https://developer.wordpress.org/reference/functions/add_action/

do_action( 'woocommerce_after_checkout_shipping_form', $wccs_custom_checkout_field_pro );

我真的不明白你想要达到什么目的...但可以尝试使用不同的钩子吗?

add_action( 'woocommerce_thankyou', 'action_checkout_order_processed', 10, 1 );

当客户到达感谢页面时,这将 运行 您的代码。 或者

add_action( 'woocommerce_order_status_processing', 'action_woocommerce_order_status_processing', 10, 1 ); 

将运行您的代码当订单状态变为处理中时。

如果有人对此有疑问,我找到了解决方案。 我修改了 includes/admin/meta-boxes/html-order-shipping.php 中的管理订单输出,并强制在每个订单上加载我的自定义方法,因此在这种情况下,用户会在前端看到正确的方法,然后我成功了仅在后端更新方法,这正是我想要实现的目标。