Search code examples
wordpresswoocommerceproducthook-woocommerceemail-notifications

Add product link to out of stock email notification in WooCommerce


I need to get the product link into out of stock emails sent to admin.

This code does not have the desired result even though I am, as far as I know, using the right filter hook? Any advice?

add_filter('woocommerce_email_content_no_stock', 'add_product_url_to_out_of_stock_email', 10, 2);
function add_product_url_to_out_of_stock_email( $message, $product ) {

    global $product; // with or without this is the same result

    return $message ."<br>\n". get_edit_post_link( $product->get_id() );

}

Solution

  • You can add/use WC_Product::get_permalink() – Product permalink to customize $message to suit your needs.

    So you get:

    function filter_woocommerce_email_content_no_stock ( $message, $product ) {
        // Edit message
        $message = sprintf( __( '%s is out of stock.', 'woocommerce' ), '<a href="' . $product->get_permalink() . '">' . html_entity_decode( wp_strip_all_tags( $product->get_formatted_name() ), ENT_QUOTES, get_bloginfo( 'charset' ) ) . '</a>' );
        
        return $message;
    }
    add_filter( 'woocommerce_email_content_no_stock', 'filter_woocommerce_email_content_no_stock', 10, 2 );
    

    IMPORTANT: This answer will not work by default because wp_mail() is used as mail function, where the content type is text/plain which does not allow using HTML

    So to send HTML formatted emails with WordPress wp_mail(), add this extra piece of code

    function filter_wp_mail_content_type() {
        return "text/html";
    }
    add_filter( 'wp_mail_content_type', 'filter_wp_mail_content_type', 10, 0 );
    

    Related: Adding product hyperlink to low stock notification email in WooCommerce