AdrianV
AdrianV

Reputation: 109

Hook JS into WooCommerce Email function

I am trying to add some JS for Trustpilot in my WooCommerce processing order emails (customer-processing-order.php). I am currently trying to just echo it with a function in functions.php like so:

add_action ('woocommerce_email_header', 'add_trustpilot_script', 9999, 3);

function add_trustpilot_script ($headers, $email_id, $order ){
$theSku = '';
foreach ( $order->get_items() as $item_id => $item ) {
          $sku = $item->get_sku();
          $theSku .= $sku . ',';
}
$tSku = substr($theSku, 0,-1);

echo '<script type="application/json+trustpilot">
   { 
      "recipientName": "'. $order->get_billing_first_name().'", 
      "recipientEmail": "'. $order->get_billing_email().'", 
      "referenceId": "'. $order->get_id().'", 
      "productSkus": ["'.$tSku.'"]
   }
</script>';
}

But the above is not working :( any help appreciated.

Upvotes: 0

Views: 351

Answers (1)

7uc1f3r
7uc1f3r

Reputation: 29624

Your code contains some minor errors

  • $order is not an argument in the woocommerce_email_header hook
  • $email->id is used in an if condition, to target the customer_processing_order email
  • $item->get_sku(); is replaced by $product->get_sku();

So you get:

function action_woocommerce_email_header( $email_heading, $email ) {    
    // Only for order processing email 
    if ( $email->id == 'customer_processing_order' ) {  
        // Get an instance of the WC_Order object
        $order = $email->object;
        
        // Is a WC_Order
        if ( is_a( $order, 'WC_Order' ) ) {
            // Empty string
            $theSku = '';
            
            foreach ( $order->get_items() as $item_id => $item ) {
                // Get an instance of corresponding the WC_Product object
                $product = $item->get_product();
                
                // Get product SKU
                $product_sku = $product->get_sku();
                
                $theSku .= $product_sku . ',';
            }
            
            $tSku = substr( $theSku, 0, -1 );

            echo '<script type="application/json+trustpilot">
            { 
                "recipientName": "' . $order->get_billing_first_name() . '",
                "recipientEmail": "' . $order->get_billing_email() . '", 
                "referenceId": "' . $order->get_id() . '", 
                "productSkus": ["' . $tSku . '"]
            }
            </script>';
        }
    }
} 
add_action( 'woocommerce_email_header', 'action_woocommerce_email_header', 10, 2 );

Note: the results can be found in the email source, one email client displays the results visually, the other does not, so it depends on which email client you use

Upvotes: 2

Related Questions