我在产品中添加了一个自定义 SKU,用于供应商 SKU 的订单确认电子邮件。我创建的内容仅适用于简单产品,不适用于可变产品。
自定义 SKU,
我将此添加到functions.php
function jk_add_custom_sku() {
$args = array(
'label' => __( 'Custom SKU', 'woocommerce' ),
'placeholder' => __( 'Enter custom SKU here', 'woocommerce' ),
'id' => 'jk_sku',
'desc_tip' => true,
'description' => __( 'This SKU is for internal use only.', 'woocommerce' ),
);
woocommerce_wp_text_input( $args );
}
add_action( 'woocommerce_product_options_sku', 'jk_add_custom_sku' );
function jk_save_custom_sku( $post_id ) {
// grab the custom SKU from $_POST
$custom_sku = isset( $_POST[ 'jk_sku' ] ) ? sanitize_text_field( $_POST[ 'jk_sku' ] ) : '';
// grab the product
$product = wc_get_product( $post_id );
// save the custom SKU using WooCommerce built-in functions
$product->update_meta_data( 'jk_sku', $custom_sku );
$product->save();
}
add_action( 'woocommerce_process_product_meta', 'jk_save_custom_sku' );
接下来我修改了电子邮件模板 email-order-items.php 添加到 SKU 部分以检查自定义 SKU 是否存在。
<?php
// Show title/image etc.
if ( $show_image ) {
echo wp_kses_post( apply_filters( 'woocommerce_order_item_thumbnail', $image, $item ) );
}
// Product name.
echo wp_kses_post( apply_filters( 'woocommerce_order_item_name', $item->get_name(), $item, false ) );
// SKU.
if ( $show_sku && $sku ) {
echo wp_kses_post( ' (#' . $sku . ')' );
// load the custom SKU
$custom_sku = get_post_meta( $product->get_id(), 'jk_sku', true );
if ( is_string( $custom_sku ) ) { // only show the custom SKU if it's set
echo "<br>" . wp_kses_post( "Custom SKU: $custom_sku" ); // change this line if needed
}
}
// allow other plugins to add additional product information here.
do_action( 'woocommerce_order_item_meta_start', $item_id, $item, $order, $plain_text );
wc_display_item_meta(
$item,
array(
'label_before' => '<strong class="wc-item-meta-label" style="float: ' . esc_attr( $text_align ) . '; margin-' . esc_attr( $margin_side ) . ': .25em; clear: both">',
)
);
// allow other plugins to add additional product information here.
do_action( 'woocommerce_order_item_meta_end', $item_id, $item, $order, $plain_text );
?>
</td>
自定义 SKU 仅显示在简单产品的电子邮件中。我需要它来处理可变产品。每个产品只有一个自定义 SKU,而不是每个可变产品。