WooCommerce 产品列表中的某些属性

问题描述 投票:0回答:1

在 WooCommerce 上的在线商店中,我使用在存档/类别页面上显示某些产品属性的代码。

add_action( 'woocommerce_before_shop_loop_item_title', 'new_template_loop_product_meta', 20 );
function new_template_loop_product_meta() {
    global $product;

    $attrs_by_cats = [
        20 => [ 'pa_size' ],

    ];

    $attr_list = [
        'Size' => 'pa_size',
    ];

    if ( ! is_object( $product ) ) {
        $product = wc_get_product( get_the_id() );
    }

    $cats = $product->get_category_ids();

    if ( ! is_array( $cats ) ) {
        return;
    }

    $attrs = [];

    foreach ( $cats as $cat ) {
        if ( isset( $attrs_by_cats[ $cat ] ) ) {
            $attrs[] = $attrs_by_cats[ $cat ];
        }
    }

    $allowed_attrs = array_unique( array_merge( [], ...$attrs ) );

    echo '<div class="custom-attributes">';

    foreach ( $attr_list as $attr_title => $attr_name ) {
        if ( in_array( $attr_name, $allowed_attrs, true ) ) {
            show_attribute( $product, $attr_title, $attr_name );
        }
    }

    echo '</div>';
}
function show_attribute( $product, $attr_title, $attr_name ) {
    if ( 'sku' === $attr_name ) {
        $attr = (string) $product->get_sku();
    } else {
        $attr = $product->get_attribute( $attr_name );
    }

    if ( '' === $attr ) {
        return;
    }

    echo '<span class="custom-attributes-text">Size: ' . esc_html( $attr ) . '</span>';
}

现在,代码在单个列表/数组中显示“Size”属性,以逗号分隔。我需要单独显示尺寸并且不使用逗号,即将每个尺寸包裹在一个跨度中并为每个尺寸制作一个边框。就像这样 - https://prnt.sc/V9LcNuB2kp9B

我已经查看了此网站上用于将属性放置在存档/类别页面上的不同选项,但没有一个适合。

如何实施?我很乐意帮助您编写代码!

php wordpress woocommerce
1个回答
0
投票

您可以使用 PHP

explode()
函数将 Size 属性术语名称的逗号分隔字符串转换为术语名称数组...然后您可以轻松地将每个尺寸嵌入标签中。

尝试用以下修改后的函数替换您的上一个函数(已注释):

function show_attribute( $product, $attr_title, $attr_name ) {
    if ( 'sku' === $attr_name ) {
        $attr = (string) esc_html( $product->get_sku() );
    } else {
        $attr = $product->get_attribute( $attr_name );

        if ( ! $attr ) {
            return;
        }
        $attr = explode( ', ', $attr ); // convert the coma separated string to an array

        $attr_arr = []; // Initialize

        // Loop through the term names
        foreach ( $attr as $term_name ) {
            // Embed each term in a span tag
            $attr_arr[] = sprintf('<span class="attr-term">%s</span>', $term_name);
        }
        // Convert back the array of formatted html term names to a string
        $attr = implode(' ', $attr_arr);
    }

    if ( '' === $attr ) {
        return;
    }

    printf( '<div class="custom-attributes-text">%s: %s</span>', $attr_title, $attr);
}

然后对于 CSS 样式,您可以添加以下规则:

.custom-attributes-text {margin-bottom:12px; color:black;}
.custom-attributes-text > span {display:inline-block; border:solid 1px #cccccc; padding:0 5px; margin:0 2px;}

你会得到类似的东西:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.