отображать количество товара на любой странице или пост по шорткоду - PullRequest
0 голосов
/ 15 мая 2019

Я хочу отобразить количество товара с помощью шорткода

// 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 голосов
/ 15 мая 2019

// 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. Был ли передан действительный идентификатор продукта или нет.2. Затем, если для Продукта включено управление запасами.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...