简体   繁体   English

WooCommerce 中是否有产品描述的简码

[英]Is there a shortcode for product description in WooCommerce

Is there any shortcode to call the product description(text field under the title)?是否有任何短代码来调用产品描述(标题下的文本字段)?

For now, I'm using another custom field to do this job but it will be better if I use the WooCommerce field.现在,我正在使用另一个自定义字段来完成这项工作,但如果我使用 WooCommerce 字段会更好。

You can build your own shortcode this way:您可以通过以下方式构建自己的短代码:

add_shortcode( 'product_description', 'display_product_description' );
function display_product_description( $atts ){
    $atts = shortcode_atts( array(
        'id' => get_the_id(),
    ), $atts, 'product_description' );

    global $product;

    if ( ! is_a( $product, 'WC_Product') )
        $product = wc_get_product($atts['id']);

    return $product->get_description();
}

Code goes in function.php file of your active child theme (active theme).代码位于活动子主题(活动主题)的 function.php 文件中。 Tested and works.测试和工作。

Examples of USAGE [product_description]用法示例[product_description]

1) In the current product page ph: 1) 在当前产品页面 ph:

echo do_shortcode( "[product_description]" );

2) In any php code providing the related product ID 2) 在任何提供相关产品 ID 的 php 代码中

echo do_shortcode( "[product_description id='37']" );

I wrote a very similar solution to @LoicTheAztec's answer above, but slightly more defensively (as his solution was breaking Elementor edits for me due to there not being a product context when it executes the shortcode on save).我写了一个与@LoicTheAztec 上面的答案非常相似的解决方案,但更具防御性(因为他的解决方案破坏了 Elementor 对我的编辑,因为它在保存时执行短代码时没有产品上下文)。

It also solves your paragraph/newline issue as the content is formatted (basically replacing newlines with <p> tags) before returning.它还可以解决您的段落/换行问题,因为内容在返回之前已格式化(基本上用<p>标签替换换行符)。

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' );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM