【问题标题】:Writing to an SQL table on order completion在订单完成时写入 SQL 表
【发布时间】:2018-06-25 20:37:14
【问题描述】:

我最近将我的 Wordpress 网站迁移到了托管服务器,但在让某个功能正常工作时遇到了问题。在我的本地服务器上对其进行测试时,它运行良好,但现在我似乎无法弄清楚为什么它不会写入我的 SQL 表。该功能在下面,任何帮助将不胜感激。我还想知道是否有一种方法可以只在我从 PayPal 收到付款时才运行 SQL 查询,如果它需要对这个程序进行大的更改,这不是问题。

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("Y-m-d", strtotime("+$duration Months")),
        'username'      => get_post_meta( $order_id, 'My Field', true ),
        'executed'      => "false",
    );

    // 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' );
}

【问题讨论】:

  • 付款后订单状态是否变为处理中?或者他们仍然在后端处于待付款状态?有时订单状态会停留在待付款状态。
  • mysql 和 sql server 都不一样,随便用吧
  • @Yamu 我注意到它处于待处理状态的问题,但截至目前,我正在手动强制更新。问题是,尽管 WooCommerce 看到了订单,但它不会写入我在同一数据库中的自定义表。

标签: php mysql wordpress paypal woocommerce


【解决方案1】:

哦,您的订单状态如下:

$statuses = array( 'processing', 'completed' ); 

但woocommerce订单状态如下:

'wc-pending','wc-processing', 'wc-on-hold' ,'wc-completed'  , 'wc-cancelled', 'wc-refunded' , 'wc-failed'

将您的数组更新为:

$statuses = array( 'wc-processing', 'wc-completed' ); 

【讨论】:

  • 我尝试将数组更新为该数组,但仍未写入 SQL 表
  • 试试 $table = "{$wpdb->prefix}checkout";而不是 $table = "checkout"; // 或 "{$wpdb->prefix}checkout";
  • 在配置文件中开启调试和调试日志查看是否有错误。
  • 所以我打开调试来检查一下,但是没有与应该写入 SQL 表的函数相关的错误
  • 看来程序正在运行“if(!empty($is_done)) return;”中的return;线。任何想法为什么会这样做?
猜你喜欢
  • 1970-01-01
  • 2012-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-18
  • 2016-04-17
  • 1970-01-01
  • 2019-09-05
相关资源
最近更新 更多