如何在自定义短代码中获取 WooCommerce 产品对象以避免错误

How to get WooCommerce product object in a custom shortcode to avoid errors

我有一个函数,我在其中尝试使用产品 ID 获取当前产品的产品简短描述,但我不断收到未捕获错误:调用成员函数 get_short_description() on bool in

我有以下短代码功能,我试图使用产品 ID 获取当前 WooCommerce 产品的产品简短描述:

function custom_product_description( $atts ) {
    global $product;

    // Shortcode attribute (or argument)
    $atts = shortcode_atts( array(
        'id'    => ''
    ), $atts, 'custom_product_description' );

    // If the "id" argument is not defined, we try to get the post Id
    if ( ! ( ! empty($atts['id']) && $atts['id'] > 0 ) ) {
       $atts['id'] = get_the_id();
    }

    // We check that the "id" argument is a product id
    if ( get_post_type($atts['id']) === 'product' ) {
        $product = wc_get_product($atts['id']);
    }

    $product_short_description = $product->get_short_description();

    return  $product_short_description;
}

但我不断收到以下错误:
未捕获的错误:调用成员函数 get_short_description() on bool in …

感谢任何帮助。

要避免您的自定义简码出现此错误,请改用以下代码:

function custom_product_description($atts){
    // Extract shortcode attributes
    extract( shortcode_atts( array(
        'id' => get_the_ID(),
    ), $atts, 'product_description' ) );
    
    global $product;

    // If the product object is not defined, we get it from the product ID
    if ( ! is_a($product, 'WC_Product') && get_post_type($id) === 'product' ) {
        $product = wc_get_product($id);
    }
    
    if ( is_a($product, 'WC_Product') ) {
        return $product->get_short_description();
    }
}
add_shortcode( 'product_description', 'custom_product_description');

代码进入活动子主题(或活动主题)的 functions.php 文件。它现在应该可以工作了。

用法:

  • 单个产品页面上没有定义的 id 参数:[product_description]
  • 以定义的有效产品 ID 作为参数:[product_description id="37"]