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

Tro*_*ler 5 php wordpress product shortcode woocommerce

是否有任何短代码来调用产品描述(标题下的文本字段)?

现在,我正在使用另一个自定义字段来完成这项工作,但如果我使用 WooCommerce 字段会更好。

Loi*_*tec 9

您可以通过以下方式构建自己的短代码:

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();
}
Run Code Online (Sandbox Code Playgroud)

代码位于活动子主题(活动主题)的 function.php 文件中。测试和工作。

用法示例 [product_description]

1) 在当前产品页面 ph:

echo do_shortcode( "[product_description]" );
Run Code Online (Sandbox Code Playgroud)

2) 在任何提供相关产品 ID 的 php 代码中

echo do_shortcode( "[product_description id='37']" );
Run Code Online (Sandbox Code Playgroud)


小智 6

我写了一个与@LoicTheAztec 上面的答案非常相似的解决方案,但更具防御性(因为他的解决方案正在破坏 Elementor 的编辑,因为它在保存时执行短代码时没有产品上下文)。

它还可以解决您的段落/换行问题,因为内容<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' );
Run Code Online (Sandbox Code Playgroud)