我正在尝试从woocommerce订单中获取信息,将其放入变量中,然后将其写入SQL数据库。我可以正确检索和处理数据。如果我手动运行它,我甚至设法将它写入数据库。
我似乎无法通过脚本获取动作挂钩。
我跟随我所看到的人们在这里做类似的事情,但到目前为止还没有奏效。我有3个主要问题:
我可以在函数中定义订单ID,
我是否需要在其他地方调用该函数,
此处理挂钩是否已正确设置为在处理付款后运行。
功能如下:
arangoexport
答案 0 :(得分:1)
此挂钩仅适用于付款订单(在“COD”,“BACS”和“支票”付款方式之外),订单状态始终设置为“正在处理或已完成”。但如果您正在测试支付网关帐户上对此进行测试,如果收到的交易反馈参数丢失,订单将显示为已付款,但仍处于“暂停”状态,因此不会触发挂钩。
我已经使用Paypal和其他信用卡支付网关对该挂钩进行了测试,并且在支付交易且订单状态设置为“正在处理或已完成”时,它已正确启动。
现在为了避免这些问题,您可以使用woocommerce_order_status_changed
来定位“处理”/“已完成”订单状态。
此外,您不应使用经典的PHP SQL连接,而应使用Wordpress / Woocommerce代码中的专用wpdb class。
下面我使用wpdb class重新访问了您的代码。这是代码:
add_action( 'woocommerce_order_status_changed', 'checkout_custom_table_insert', 20, 4 );
function checkout_custom_table_insert( $order_id, $old_status, $new_status, $order ){
// Only for 'processing' and 'completed' order status changes
$statuses = array( 'processing', 'completed' );
if ( ! in_array( $new_status, $statuses ) ) return;
// Check if data has been already updated (avoid repetitions)
$is_done = get_post_meta( $order_id, '_checkout_table_updated', true );
if( ! empty($is_done) ) return; // We exit if it has been already done
global $wpdb;
// Loop through order items
foreach ($order->get_items() as $item){
$product = $item->get_product(); // Get the variation product object
// Choose in the array which data you want to insert (each line is a table column)
$args = array(
'rank' => $product->get_attribute( 'pa_rank' ),
'money' => $product->get_attribute( 'pa_money' ),
'spawner' => $product->get_attribute( 'pa_spawner' ),
'permission' => $product->get_attribute( 'pa_permission' ),
'kit' => $product->get_attribute( 'pa_kit' ),
'crate' => $product->get_attribute( 'pa_crate' ),
'stag' => $product->get_attribute( 'pa_stag' ),
'duration' => $product->get_attribute( 'pa_duration' ),
'end_date' => date("d/m/Y", strtotime("+ $duration Months")),
);
// The SQL INSERT query
$table = "checkout" // or "{$wpdb->prefix}checkout";
$wpdb->insert( $table, $args ); // Insert the data
}
// Mark this task as done for this order
update_post_meta( $order_id, '_checkout_table_updated', '1' );
}
代码进入活动子主题(或活动主题)的function.php文件。
这应该更好......