通过短代码显示 WooCommerce 产品尺寸

时间:2021-01-18 17:08:06

标签: php wordpress woocommerce product shortcode

我正在为产品创建自定义布局(使用 Elementor) - 我需要的是在我创建的自定义选项卡中显示产品的尺寸。

是否有产品尺寸的简码? (如果有所不同,某些产品也是可变的)

我设法获得了一些代码来在短代码中显示长描述(见下文),但是我不够先进,不知道如何让它显示产品尺寸(长度、宽度、高度 - 理想情况下每个单独一行)

这是我发现有效的长描述代码...

function custom_product_description($atts){
    global $product;

    try {
        if( is_a($product, 'WC_Product') ) {
            return wc_format_content( $product->get_description("shortcode") );
        }

        return "Product description shortcode run outside of product context";
    } catch (Exception $e) {
        return "Product description shortcode encountered an exception";
    }
}
add_shortcode( 'custom_product_description', 'custom_product_description' );

有人可以帮助我通过短代码显示产品尺寸吗?

1 个答案:

答案 0 :(得分:0)

您可以使用以下简单的代码片段,通过短代码显示产品尺寸:

add_shortcode( 'product_dimensions', 'display_product_dimensions' );

function display_product_dimensions( $atts ){
    // Extract shortcode attributes
    extract( shortcode_atts( array(
        'id' => '',
    ), $atts, 'product_dimensions' ) );

    if( $id == '' ) {
        global $product;

        if( ! is_a($product, 'WC_Product') ) {
            $product = wc_get_product( get_the_id() );
        }
    }

    return method_exists( $product, 'get_dimensions' ) ? wc_format_dimensions($product->get_dimensions(false)) : '';
}

代码位于活动子主题(或活动主题)的functions.php 文件中。它应该有效。

用法:

  • 在 WooCommerce 产品单页上:[product_dimensions]
  • 具有已定义 ID (例如产品 ID 35)的任何位置[product_dimensions id="35"]