来自 Essential Grid 的 PHP 脚本的语法错误,该脚本在 WooCommerce 中显示“已售罄”徽章

Syntax error with PHP script from Essential Grid that shows "Sold out" badges in WooCommerce

提问人:Nikola Styrcikova 提问时间:11/9/2023 更新时间:11/9/2023 访问量:19

问:

我正在尝试将已售罄的产品放入我的 WooCommerce 电子商店徽章中。

插件是可用的,但我正在使用 Essential Grid 插件来显示产品(所以经典插件不在桌面上)。

有一个解决方案(在这里描述),直接来自Essential Grid开发人员,但它(显然)在第15行包含一个语法错误,描述如下:

$html = ‘<p class=”stock in-stock”>In stock</p>’;

下面列出了整个代码。

由于我是PHP的完全新手,因此我将不胜感激该代码的修复,以便我可以使用它。谁能帮忙?;)

add_shortcode( ‘stock_status’, ‘display_product_stock_status’ );

function display_product_stock_status( $atts) {
    $atts = shortcode_atts(
        array(‘id’  => get_the_ID() ),
        $atts, ‘stock_status’
    );
 
if( intval( $atts[‘id’] ) > 0 && function_exists( ‘wc_get_product’ ) ){
    $product = wc_get_product( $atts[‘id’] );
 
    $stock_status = $product->get_stock_status();
 
    if ( ‘instock’ == $stock_status) {        
$html = ‘<p class=”stock in-stock”>In stock</p>’;  
    } else {
$html = ‘<p class=”stock out-of-stock”>Out of stock</p>’;      
    }
}
return $html;
}

我试图找出如何修复语法错误,但由于我不懂PHP语法,我无法解决它。

PHP 语法 网格

评论

1赞 Barmar 11/9/2023
代码中的引号类型错误。您需要使用直引号,而不是大引号。使用适当的代码编辑器,或在编辑代码时关闭“智能引号”。

答:

1赞 Lasse 11/9/2023 #1

似乎他们的例子是使用“智能”引号。只需将它们替换为常规的直单引号和双引号:

add_shortcode( 'stock_status', 'display_product_stock_status' );

function display_product_stock_status( $atts) {
    $atts = shortcode_atts(
        array('id'  => get_the_ID() ),
        $atts, 'stock_status'
    );
 
    if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
        $product = wc_get_product( $atts['id'] );
    
        $stock_status = $product->get_stock_status();
    
        if ( 'instock' == $stock_status) {        
            $html = '<p class="stock in-stock">In stock</p>';  
        } else {
            $html = '<p class="stock out-of-stock">Out of stock</p>';      
        }
    }

    return $html;
}