在任何页面或短代码中显示产品数量

时间:2019-05-15 05:38:56

标签: php wordpress

我想使用简码显示产品数量

// display product stock quantity open
if( !function_exists('show_specific_product_quantity') ) {

function show_specific_product_quantity( $atts ) {

    // Shortcode Attributes
    $atts = shortcode_atts(
        array(
            'id' => '', // Product ID argument
        ),
        $atts,
        'product_qty'
    );

    if( empty($atts['id'])) return;

    $stock_quantity = 0;

    $product_obj = wc_get_product (intval( $atts['id'] ) );
    $stock_quantity = $product_obj->get_stock_quantity();

    if( $stock_quantity > 0 ) return $stock_quantity;

}

add_shortcode( 'product_qty', 'show_specific_product_quantity' );

}// display product stock quantity close

1 个答案:

答案 0 :(得分:0)


// Check if function show_specific_product_quantity exists or not.
if ( ! function_exists( 'show_specific_product_quantity' ) ) {

    /**
     * Return product stock quantity.
     *
     * @param  array $atts Shortcode attritube.
     * @return int         Number of stock for the particular product ID.
     */
    function show_specific_product_quantity( $atts ) {

        // Shortcode Attributes.
        $atts = shortcode_atts(
            array(
                'id' => '', // Product ID argument.
            ),
            $atts,
            'product_qty'
        );

        if ( empty( $atts['id'] ) ) {
            return;
        }

        $stock_quantity = 0;

        // Check if pass Product ID is valid WooCommerce product.
        if ( 'product' !== get_post( $atts['id'] )->post_type ) {
            return 'Kindly check product ID';
        }

        $product_obj = wc_get_product( intval( $atts['id'] ) );

        // Check if Manage stock is enable or not.
        if ( $product_obj->get_manage_stock() ) {
            $stock_quantity = $product_obj->get_stock_quantity();
        } else {
            return 'Manage stock not available for this product.';
        }

        if ( $stock_quantity > 0 ) {
            return $stock_quantity;
        } else {
            return 'No stock available.';
            ;
        }

    }
}

// Add Shortcode to get product quantity
// i.e. [product_qty id="{product_id_number}"].
add_shortcode( 'product_qty', 'show_specific_product_quantity' );

需要再检查几件事,即  1.是否通过了有效的产品ID。  2.然后,如果为该产品启用了管理库存。