如何在过滤器“ woocommerce_email_attachments”中获取订单ID

时间:2019-07-27 11:55:57

标签: wordpress woocommerce

我想将发票以PDF格式附加到WooCommerce邮件中。适用于静态PDF(例如条款和条件),但是我需要使用可变PDF文件(例如发票)的选项。

我使用此过滤器:

add_filter( 'woocommerce_email_attachments', 'attach_pdf_to_email', 10, 3);

和此功能:

function attach_pdf_to_email ( $attachments, $status , $object ) {

$pdf_path = ABSPATH . "wp-content/uploads/terms.pdf";
$attachments[] = $pdf_path;

return $attachments;

}

完美运行。现在,我想将$ pdf_path更改为此:

$pdf_path = ABSPATH . "wp-content/uploads/terms" . $order_id . ".pdf";

但是我无法获得$ order_id。

我尝试过:

global $order;

// First try
$order_id = $order->id;

// Second try
$order_id = $order->get_id();

// Third and fourth try (like above)
global $post;

问题在于,过滤器既不发送订单,也不发送订单ID。有什么方法或想法,我如何实现?

3 个答案:

答案 0 :(得分:1)

尝试此代码。

add_filter( 'woocommerce_email_attachments', 'attach_pdf_to_email', 10, 3);

function attach_agb_to_email ( $attachments, $status , $order ) {

    if ( empty( $order ) ) {
        return $attachments;
    }

    $order_id = $order->id;
    $pdf_path = ABSPATH . "wp-content/uploads/terms" . $order_id . ".pdf";

    $attachments[] = $pdf_path;

    return $attachments;

}

答案 1 :(得分:1)

您可以从$object获取订单ID。 尝试下面的代码,我已经尝试过您的代码并对其进行编辑以获得订单ID

function attach_pdf_to_email($attachments, $status, $object) {
    $order_id = method_exists($object, 'get_id') ? $object->get_id() : $object->id;

    $pdf_path = ABSPATH . "wp-content/uploads/terms" . $order_id . ".pdf";
//  $pdf_path = ABSPATH . "wp-content/uploads/terms.pdf";

    $attachments[] = $pdf_path;

    return $attachments;
}

add_filter('woocommerce_email_attachments', 'attach_pdf_to_email', 10, 3);

答案 2 :(得分:0)

尝试以下代码:

 add_filter( 'woocommerce_email_attachments', 'wh_attach_document_into_email', 10, 3 );
    function wh_attach_document_into_email ( $attachments, $email_id, $object ){
        $order_id = $object->order->get_order_number();
        //`enter code here`
        return $attachments;
    }

经过测试的Woo> 3.8.0