标签:woocommerce

以下是与标签 “woocommerce” 相关联的文章

woocommerce 学习

controller

  • 页面加载例子

    function woocommerce_account_orders( $current_page ) {
      $current_page = empty( $current_page ) ? 1 : absint( $current_page );
      $customer_orders = wc_get_orders( apply_filters( 'woocommerce_my_account_my_orders_query', array( 'customer' => get_current_user_id(), 'page' => $current_page, 'paginate' => true ) ) );
    
      wc_get_template(
        'myaccount/orders.php',
        array(
          'current_page' => absint( $current_page ),
          'customer_orders' => $customer_orders,
          'has_orders' => 0 < $customer_orders->total,
        )
      );
    }
    
  • wc_get_template 传入 array 参数,可以被业面直接使用。

支付处理

  • 处理 ipn 响应
class WC_Gateway_Paypal_IPN_Handler extends WC_Gateway_Paypal_Response
  • 更新 order metadata 状态
update_post_meta( $order->id, 'Payment type', $transaction_result['payment_type'] );
  • 发送邮件方法
$mailer = WC()->mailer();
$message = $mailer->wrap_message( $subject, $message );
$mailer->send( ! empty( $new_order_settings['recipient'] ) ? $new_order_settings['recipient'] : get_option( 'admin_email' ), strip_tags( $subject ), $message );
  • 订单成功 hook
function wc_paying_customer( $order_id ) {
  $order = wc_get_order( $order_id );

  if ( $order->user_id > 0 && 'refund' !== $order->order_type ) {
    update_user_meta( $order->user_id, 'paying_customer', 1 );

    $old_spent = absint( get_user_meta( $order->user_id, '_money_spent', true ) );
    update_user_meta( $order->user_id, '_money_spent', $old_spent + $order->order_total );
  }
  if ( $order->user_id > 0 && 'simple' === $order->order_type ) {
    $old_count = absint( get_user_meta( $order->user_id, '_order_count', true ) );
    update_user_meta( $order->user_id, '_order_count', $old_count + 1 );
  }
}
add_action( 'woocommerce_order_status_completed', 'wc_paying_customer' );
  • 查找商品

商品的本质是一个 post,wc 通过 product_factory 把 post 转换成 product。 post 中保存了 product id 和 classname,通过反射创建了 product 对象。

$query_args = array(
  'fields'      => 'ids',
  'post_type'   => 'product',
  'post_status' => 'publish',
  'meta_query'  => array(),
);
$query = new WP_Query( $query_args );
$products = array();
foreach ( $query->posts as $product_id ) {
  $products[] = wc_get_product($product_id);
}