I can\'t seem to find a way of adding related products or cross sells to order emails in WooCommerce, and it\'s hurting my brain. I\'m sure it must be possible but can\'t seem t
You can put this in your child theme's functions.php
file:
// product suggestion in order mail
function order_mail_product_suggestion($atts) {
$atts=shortcode_atts(
array(
'id' => '',
), $atts, 'order_mail_product_suggestion');
$orderId = esc_attr($atts['id']);
$order = wc_get_order( (int)$orderId );
$items = $order->get_items();
$cat = array();
$pid = array();
foreach ( $items as $item ) {
$pid[] = $item->get_product_id();
$terms = wp_get_post_terms($item->get_product_id(),'product_cat',array('fields'=>'ids'));
foreach ( $terms as $term ) {
$cat[] = $term;
}
}
$uniuqcat = array_unique($cat);
$uniuqpid = array_unique($pid);
$html = '';
$args = array(
'post_type' => 'product',
'stock' => 1,
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'posts_per_page' => '20',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => implode(',', $uniuqcat),
'operator' => 'IN'
),
array(
'taxonomy' => 'product_visibility',
'field' => 'slug',
'terms' => 'exclude-from-catalog',
'operator' => 'NOT IN'
)
)
);
$loop = new WC_Product_Query($args);
$products = $loop->get_products();
if ($products) {
$html .= '';
$html .= 'PLUS, MORE THINGS YOU MAY LIKE
';
$html .= '';
$html .= '';
$html .= '';
$i=0;
foreach ( $products as $product ) {
if (in_array($product->get_id(), $pid)) {
continue;
}
$html .= '';
if (has_post_thumbnail( $product->get_id() )) {
$html .= get_the_post_thumbnail($product->get_id(), 'shop_catalog');
} else {
$html .= '
';
}
$html .= ''.esc_attr($product->get_title() ? $product->get_title() : $product->get_id()).'
';
$html .= '';
$i++;
if($i==4) break;
}
$html .= ' ';
$html .= '';
$html .= '
';
$html .= '';
}
// now return the preapred html
return $html;
}
// register shortcode
add_shortcode('email_product_suggestion', 'order_mail_product_suggestion');
And then call the function in email templates like this:-
// Product suggestions
$order = $email->object;
if ( $order ) {
$id = $order->get_id();
echo do_shortcode( '[email_product_suggestion id="'.$id.'" ]' );
}
This will show products from the category where the current order item belongs, and exclude items that are already in the order.