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

Display Woocommerce product attribute on archive page

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

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. 对于存档页面(但不是单个产品页面!)我希望在产品缺货时更改文本。与其完全不显示,我更希望它“售罄”。

请注意,Whosebug 上的规则是当时的一个问题。您可以使用自定义函数,您将在每个挂钩函数上调用该函数,例如:

// 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 pages
add_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 pages
add_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 notifications
add_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() ) );
}

应该可以。

On archive pages only when product is not in stock, it will displays "Sold Out".