在存档页面上显示 Woocommerce 产品属性

我已为我的产品设置了交货时间属性。我使用以下功能将其显示在产品档案、单个产品页面、订单和电子邮件通知上:


add_action( 'woocommerce_single_product_summary', 'product_attribute_delivery', 27 );

function product_attribute_delivery(){

    global $product;

    $taxonomy = 'pa_delivery';

    $value = $product->get_attribute( $taxonomy );

    if ( $value && $product->is_in_stock() ) {

        $label = get_taxonomy( $taxonomy )->labels->singular_name;

        echo '<small>' . $label . ': ' . $value . '</small>';

    }

}


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

function custom_item_meta($item_id, $item, $order, $plain_text)

    {   $productId = $item->get_product_id();

    $product = wc_get_product($productId);

    $taxonomy = 'pa_delivery';

    $value = $product->get_attribute($taxonomy);

    if ($value) {

        $label = get_taxonomy($taxonomy)->labels->singular_name;

        echo  '<small>' . $label . ': ' . $value . '</small>';

    }

}


add_action( 'woocommerce_after_shop_loop_item', 'product_attribute_delivery_shop', 1 );

function product_attribute_delivery_shop(){

    global $product;

    $taxonomy = 'pa_delivery';

    $value = $product->get_attribute( $taxonomy );

    if ( $value && $product->is_in_stock() ) {

        $label = get_taxonomy( $taxonomy )->labels->singular_name;

        echo '<small>' . $label . ': ' . $value . '</small>';

    }

}

我有两个问题:

  1. 有没有办法结合这些功能来优化和清理代码?

  2. 对于存档页面(但不是单个产品页面!),我希望当产品没有库存时更改文本。我希望它“已售完”,而不是根本不显示。



翻阅古今
浏览 63回答 1
1回答

子衿沉夜

您可以使用将在每个挂钩函数上调用的自定义函数,例如:// Custom function that handle the code to display a product attribute function custom_display_attribute( $product, $taxonomy = 'pa_delivery') {    $value = $product->get_attribute( $taxonomy );    if ( ! empty($value) && $product->is_in_stock() ) {        $label = wc_attribute_label( $taxonomy );        echo '<small>' . $label . ': ' . $value . '</small>';    }}// On product archive pagesadd_action( 'woocommerce_after_shop_loop_item', 'product_attribute_delivery_archives', 1 );function product_attribute_delivery_archives() {    global $product;    custom_display_attribute( $product );    // When product is out of stock displays "Sold Out"    if ( ! $product->is_in_stock() ) {        echo __("Sold Out", "woocommerce");    }}// On product single pagesadd_action( 'woocommerce_single_product_summary', 'product_attribute_delivery_single', 27 );function product_attribute_delivery_single() {    global $product;    custom_display_attribute( $product );}// On orders and email notificationsadd_action('woocommerce_order_item_meta_end', 'custom_item_meta', 10, 4 );function custom_item_meta( $item_id, $item, $order, $plain_text ) {       custom_display_attribute( wc_get_product( $item->get_product_id() ) );}它应该有效。只有当产品没有库存时,存档页面才会显示“已售完”。
打开App,查看更多内容
随时随地看视频慕课网APP