将产品类别添加到 WooCommerce 电子邮件通知

Add product category to WooCommerce Email Notifications

我正在尝试将产品类别添加到电子邮件通知中。自定义字段(时间和日期)有效,但产品类别显示为 "Array"。

function render_product_description($item_id, $item, $order){
    $_product = $order->get_product_from_item( $item );
    echo "<br>" . $_product->post->post_content;
    echo "<br>";
    echo '<p><strong>Time:</strong><br />';
        echo get_post_meta($_product->id, 'time', true) .'</p>';

    echo '<p><strong>Category:</strong><br />';
        echo wp_get_post_terms($_product->id, 'product_cat', true) .'</p>';

    echo '<p><strong>Date:</strong><br />';
        echo get_post_meta($_product->id, 'date', true) .'</p>';
}

add_action('woocommerce_order_item_meta_end', 'render_product_description',10,3);

You can use implode() function that join array values in a string.

我还添加了一个额外的空值检查

function render_product_description( $item_id, $item, $order, $plain_text ) {
    // Get product id
    $product_id = $item->get_product_id();

    // Get product
    $product = $item->get_product();

    // Product content
    $product_content = $product->post->post_content;

    // NOT empty
    if ( ! empty ( $product_content ) ) {
        echo '<p>' . $product_content . '</p>'; 
    }

    // Get post meta
    $time = get_post_meta( $product_id, 'time', true );

    // NOT empty
    if ( ! empty ( $time ) ) {
        echo '<p><strong>Date:</strong><br />' . $time . '</p>';    
    }

    // Get terms
    $term_names = wp_get_post_terms( $product_id, 'product_cat', ['fields' => 'names'] );

    // NOT empty
    if ( ! empty ( $term_names ) ) {
        echo '<p><strong>Categories:</strong><br />' . implode( ", ", $term_names ) . '</p>';   
    }

    // Get post meta
    $date = get_post_meta( $product_id, 'date', true );

    // NOT empty
    if ( ! empty ( $date ) ) {
        echo '<p><strong>Date:</strong><br />' . $date . '</p>';    
    }
}

add_action( 'woocommerce_order_item_meta_end', 'render_product_description', 10, 4 );