为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
翻阅古今 2023-10-22 21:09:13
我已为我的产品设置了交货时间属性。我使用以下功能将其显示在产品档案、单个产品页面、订单和电子邮件通知上: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 回答

?
子衿沉夜

TA贡献1828条经验 获得超3个赞

您可以使用将在每个挂钩函数上调用的自定义函数,例如:


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

}

它应该有效。


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


查看完整回答
反对 回复 2023-10-22
  • 1 回答
  • 0 关注
  • 60 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信