【问题标题】:Show specific multiple attributes in WooCommerce product page在 WooCommerce 产品页面中显示特定的多个属性
【发布时间】:2023-02-11 18:45:43
【问题描述】:

我正在尝试在 WooCommerce 产品页面上显示多个属性。我找到了这段代码,但它只适用于一个属性。我不是 PHP 开发人员,所以我无法编写代码来获取更多属性。谁能帮我?

function get_product_attributes_shortcode( $atts ) {
    extract( shortcode_atts( array(
        'id'    => get_the_ID(),
    ), $atts, 'display-attributes' ) );

    global $product;

    if ( ! is_a($product, 'WC_Product') ) {
        $product = wc_get_product( $id );
    }
    if ( is_a($product, 'WC_Product') ) {
        $styletypes = $product->get_attribute( 'styletypes' );
        return '<div class="product-attributes"><strong>Styletype</strong>: ' . $styletypes . '<div>';
    }
}
add_shortcode( 'display-attributes', 'get_product_attributes_shortcode' );

【问题讨论】:

  • $product->get_attributes() 将返回所有属性的数组

标签: php woocommerce attributes hook-woocommerce hook-wordpress


【解决方案1】:
function get_product_attributes_shortcode($atts) {
    
    extract(shortcode_atts(array('id' => get_the_ID(),), $atts, 'display-attributes'));

    global $product;

    if (!is_a($product, 'WC_Product')) {
        $product = wc_get_product($id);
    }
    if (is_a($product, 'WC_Product')) {
        $attr_str = '<div class="product-attributes">';
        foreach ($product->get_attributes() as $attr_key => $attr) {
            $attr_str.= '<strong>'.$attr['name'].'</strong>: ';
            foreach ($attr['options'] as $attr_opt) {
                $attr_str.= $attr_opt .' | ';
            }
            $attr_str = rtrim($attr_str, ' | ');
            $attr_str.= '<br/>';
        }
        $attr_str.= '</div>';
        return $attr_str;
    }
}

add_shortcode('display-attributes', 'get_product_attributes_shortcode');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 2020-12-13
    • 2020-01-25
    • 2018-09-11
    • 2018-10-02
    • 2022-07-26
    相关资源
    最近更新 更多