Neil requested the following code from my WordPress AI Code Generator.
create a new woocommerce email and send this email if a product is in a certain product category, include how to create a email template and save that in the child theme directory
The robot generated the following code:
Here is a PHP Code Snippet to create a new WooCommerce email and send it if a product is part of a certain product category.
1. The first step is to create a new email class in your plugin/theme.
“`php
if ( ! class_exists( 'NM_WC_Product_Category_Email' ) ) :
class NM_WC_Product_Category_Email extends WC_Email {
function __construct() {
$this->id = 'nm_wc_product_category_email';
$this->title = 'Product Category Email';
$this->description= 'An email sent if a product is in a specific category';
$this->heading = 'Product Category Email';
$this->subject = 'You have a product from category XYZ';
$this->template_html = 'emails/nm-wc-product-category-email.php';
$this->template_plain = 'emails/plain/nm-wc-product-category-email.php';
// Call parent constructor to load any other defaults not explicity defined here
parent::__construct();
}
public function trigger( $order_id ) {
if ( $order_id ) {
$this->object = wc_get_order( $order_id );
$this->recipient = $this->object->get_billing_email();
return $this->send( $this->get_recipient(), $this->get_subject(), $this->get_content(), $this->get_headers(), $this->get_attachments() );
}
}
}
endif;
“`
2. Add the new email to WooCommerce
“`php
add_filter( 'woocommerce_email_classes', 'nm_add_wc_product_category_email' );
function nm_add_wc_product_category_email( $email_classes ) {
// Include our custom email class
include_once 'NM_WC_Product_Category_Email.php';
// Add the email class to the list of WooCommerce email classes
$email_classes['NM_WC_Product_Category_Email'] = new NM_WC_Product_Category_Email();
return $email_classes;
}
“`
3. Trigger the Email when an Order's Product is in a Specific Category
“`php
add_action( 'woocommerce_order_status_completed', 'nm_maybe_send_product_category_email', 10, 2 );
function nm_maybe_send_product_category_email( $order_id, $order ) {
foreach ( $order->get_items() as $item_id => $item ) {
$product_id = $item