Search code examples
phpwordpresswoocommercehook-woocommerceemail-notifications

Adding product hyperlink to low stock notification email in WooCommerce


By default, the low stock notification email contains this text.

  • "Product-title" is low in stock. There are "XX" left.

I want to edit this message, in order to add the product hyperlink to the product title.


I have found that I can use the following filter hook for this

add_filter( 'woocommerce_email_content_low_stock', 'low_stock_dspixel', 10, 2 );

function low_stock_dspixel( $message, $product ) {

    $message = sprintf(/* translators: 1: product name 2: items in stock */
            __( '%1$s is low in stock. There are %2$d left.', 'woocommerce' ),
            html_entity_decode( wp_strip_all_tags( $product->get_formatted_name() ), ENT_QUOTES, get_bloginfo( 'charset' ) ),
            html_entity_decode( wp_strip_all_tags( $product->get_stock_quantity() ) )
        );
 
    return $message;
}

How can I further adjust this to add the product hyperlink?


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_low_stock ( $message, $product ) {
        // Edit message
        $message = sprintf(
            /* translators: 1: product name 2: items in stock */
            __( '%1$s is low in stock. There are %2$d left.', 'woocommerce' ),
            '<a href="' . $product->get_permalink() . '">' . html_entity_decode( wp_strip_all_tags( $product->get_formatted_name() ), ENT_QUOTES, get_bloginfo( 'charset' ) ) . '</a>',
            html_entity_decode( wp_strip_all_tags( $product->get_stock_quantity() ) )
        );
        
        return $message;
    }
    add_filter( 'woocommerce_email_content_low_stock', 'filter_woocommerce_email_content_low_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: Add product link to out of stock email notification in WooCommerce