通过某些 WooCommerce 订单,收集数据,然后通过电子邮件发送结果

Go through certain WooCommerce orders, collect data and then send the results via email

我的代码的目的是处理昨天的所有订单。 然后我想要:

一起计数,然后通过 WordPress wp_mail() 函数发送结果。

出于某种原因,它甚至从未发送过电子邮件。有人可以告诉我我的代码有什么问题吗?我想念什么吗?有什么建议吗?

<?php
define('WP_USE_THEMES', false);


require( dirname( __FILE__ ) . '/wp-load.php' );


function dcwd_status_set_html_content_type() {
  return 'text/html';
}

$yesterday = date( 'Y-m-d', strtotime( '-1 days' ) );

$args = array(
    'date_created' => $yesterday,
);
$orders = wc_get_orders( $args );

$subtotal = 0.0;
$gratuity = 0.0;
$taxxes = 0.0;
if ( count( $orders ) ) {
    $orders_by_status = array();
    foreach ( $orders as $order ) {
        $eachordersubtotal = $order->get_subtotal();
        $eachordersubtotal + $subtotal;
        $eachordergratuity = $order->get_fees();
        $eachordergratuity + $gratuity;
        $eachordertaxxes = $order->get_taxxes();
        $eachordertaxxes + $taxxes;
}
$subtotalstring = sprintf("%.3f", $subtotal);
$gratuitystring = sprintf("%.3f", $gratuity);
$taxxesstring = sprintf("%.3f", $taxxes);
$to = 'myname@myemail.com';
$subject = 'Order totals for yesterday';
$body = $subtotalstring, $gratuitystring, $taxxesstring;

wp_mail($to, $subject, $body)
?>

你的代码有很多错误

  • $orders_by_status 已定义,但未使用
  • $order->get_fees() 将 return 一个数组,而不是一个整数
  • $order->get_taxxes() 应该是 $order->get_taxes(),但是这也会 return 一个数组,所以使用 $order->get_total_tax() 而不是
  • $eachordersubtotal + $subtotal 应替换为 $eachordersubtotal += $subtotal
  • wp_mail() 处的 $headers 缺失

所以你得到:

// Date
$yesterday = date( 'Y-m-d', strtotime( ' -1 days ' ) );

// Args
$args = array(
    'date_created' => $yesterday,
);

// Get WC orders
$orders = wc_get_orders( $args );

// Initialize
$subtotal = 0;
$gratuity = 0;
$taxes = 0;

// NOT empty
if ( ! empty ( $orders ) ) {
    foreach ( $orders as $order ) {
        // DEBUG information, removed if desired
        echo '<p>ID = ' . $order->get_id() . '</p>';
        
        // Get subtotal
        $subtotal += $order->get_subtotal();
        
        // Get fees
        foreach ( $order->get_fees() as $fee_id => $fee ) {
            $gratuity += $fee['line_total'];
        }

        // Get tax
        $taxes += $order->get_total_tax();
    }
}

// Send e-mail
$to = 'myname@myemail.com';
$subject = 'Order totals for yesterday';
$body = '<p>Subtotal = ' . $subtotal . '</p><p>Gratuity = ' . $gratuity . '</p><p>Taxes = ' . $taxes . '</p>';
$headers = array( 'Content-Type: text/html; charset=UTF-8' );

wp_mail( $to, $subject, $body, $headers );