简体   繁体   English

将产品类别添加到 WooCommerce Email

[英]Add product category to WooCommerce Email Notifications

I'm trying to add product category to the email notification.我正在尝试将产品类别添加到 email 通知中。 The custom fields (Time and Date) work but the product category is displaying as an "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.您可以使用implode() function 将数组值连接到字符串中。

I also added an extra check for empty values我还添加了对空值的额外检查

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 );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM