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

时间:2020-08-21 16:59:04

标签: php wordpress function woocommerce product

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

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

1 个答案:

答案 0 :(得分:1)

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

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

应该可以。

仅当产品没有库存时,才在存档页面上显示“已售完”。