通过简码显示 WooCommerce 产品尺寸

Display WooCommerce Product Dimensions via a 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' );

谁能帮我通过短代码显示产品尺寸?

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

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"]