shortCode在WooCommerce产品页面中显示产品名称和价格页面

问题描述 投票:0回答:2

我需要在不使用产品ID的情况下通过“产品”页面中的短代码显示产品标题和当前价格。

我是指我的代码自动从当前产品页面中自动检测产品ID,我使用短代码并获取标题和价格。

例如,这个示例,我必须使用类似短代码内的特定ID [iw_product_price id ='']来显示产品价格。

// Get WooCommerce product price by ID via shortcode: [iw_product_price id=''] function iw_product_price_shortcode( $atts ) { $atts = shortcode_atts( array( 'id' => null, ), $atts, 'bartag' ); $html = ''; if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){ $_product = wc_get_product( $atts['id'] ); $html = $_product->get_price_html(); } return $html; } add_shortcode( 'iw_product_price', 'iw_product_price_shortcode' ); // Get WooCommerce product name by ID via shortcode: [iw_product_name id=''] function iw_product_name_shortcode( $atts ) { $atts = shortcode_atts( array( 'id' => null, ), $atts, 'bartag' ); $html = ''; if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){ $_product = wc_get_product( $atts['id'] ); $html = $_product->get_title(); } return $html; } add_shortcode( 'iw_product_name', 'iw_product_name_shortcode' );

以下快捷代码将检测产品ID(或产品对象),并将以WooCommerce产品页面中的格式产品价格显示产品名称:
php wordpress woocommerce product shortcode
2个回答
2
投票
add_shortcode( 'product_name_price', 'get_product_name_price_shortcode' ); function get_product_name_price_shortcode( $atts ) { // Extract shortcode attributes extract( shortcode_atts( array( 'id' => get_the_ID(), ), $atts, 'product_name_price' ) ); global $product; $is_a_product = is_a($product, 'WC_Product'); if( ! $is_a_product && 'product' === get_post_type( $id ) ){ $product = wc_get_product( $id ); // get the product object from the ID } if ( $is_a_product ) { return '<span class="product-name">' . $product->get_name() . '</span> <br>' . $product->get_price_html(); } }

用作简单的简编码:

[product_name_price]

使用产品ID参数作为短代码:

[product_name_price id='28']


    

只能只有价格,而不是名称product
thanks


0
投票

© www.soinside.com 2019 - 2025. All rights reserved.