在 WooCommerce 中显示附加信息之前检查尺寸、属性和/或重量

Check for Dimension, Attributes and/ or weight before showing Additional Information in WooCommerce

默认情况下,WooCommerce 使用选项卡(附加信息、描述和评论),通过使用下面的代码,我删除了选项卡并使用挂钩 woocommerce_after_single_product_summary 将它们的内容放入产品页面。

正如您在代码中看到的,我选择不显示附加信息内容,因为我无法弄清楚如何使用下面的代码实现这一行,如果没有属性、维度,它就不会显示或重量。如果有任何这些属性,请显示附加信息。

这是我无法进入下面代码的行: if ($product -> has_attributes() || $product -> has_dimensions() || $product -> has_weight()) {

add_action( 'woocommerce_after_single_product_summary', 'cac_remove_product_tabs', 2 );
function cac_remove_product_tabs(){
    remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_product_data_tabs', 10 );
    add_action( 'woocommerce_after_single_product_summary', 'cac_display_as_one_product_page', 10 );
}
function cac_display_as_one_product_page() {
    wc_get_template( 'single-product/tabs/description.php' );
    //wc_get_template('single-product/tabs/additional-information.php');
    comments_template();
}

关于如何使这项工作有任何想法吗?感谢您提出任何改进意见或提示。

不需要,下面已经说明了…

模板 single-product/tabs/additional-information.php 使用 wc_display_product_attributes() 模板函数加载产品重量、尺寸和产品属性,该函数挂在 woocommerce_product_additional_information 操作挂钩中。

function wc_display_product_attributes( $product ) {
    wc_get_template( 'single-product/product-attributes.php', array(
        'product'            => $product,
        'attributes'         => array_filter( $product->get_attributes(), 'wc_attributes_array_filter_visible' ),
        'display_dimensions' => apply_filters( 'wc_product_enable_dimensions_display', $product->has_weight() || $product->has_dimensions() ),
    ) );
}

因此,正如您所见,它们中的每一个都在被模板显示之前先进行过滤 single-product/product-attributes.php,其中通过某些条件检查产品重量、尺寸和产品属性以避免空值:

你的体重 (第 26 行):

<?php if ( $display_dimensions && $product->has_weight() ) : ?>

对于维度,您有 (第 33 行)

<?php if ( $display_dimensions && $product->has_dimensions() ) : ?>

商品属性:如果没有商品属性,则返回空数组,不显示任何内容。

所以你不需要使用 :

 if ($product -> has_attributes() || $product -> has_dimensions() || $product -> has_weight()) { }

加法

如果标题没有数据显示,需要使用:

add_filter( 'woocommerce_product_additional_information_heading', 'custom_product_additional_information_heading' );
function custom_product_additional_information_heading( $heading ) {
    global $product;

    $attributes = array_filter( $product->get_attributes(), 'wc_attributes_array_filter_visible' );

    return $product->has_weight() && $product->has_dimensions() && sizeof($attributes) > 0 ? $heading : false;
}

代码进入活动 child 主题(或活动主题)的 function.php 文件。测试和工作。