无需指定商品ID的WooCommerce商品标题与价格短代码需求
自动识别当前商品页面的WooCommerce短代码(无需指定ID)
你可以修改现有短代码,让它在未指定id参数时自动获取当前商品页面的商品ID,具体代码如下:
// 显示当前商品价格的短代码 [iw_product_price] function iw_product_price_shortcode( $atts ) { $atts = shortcode_atts( array( 'id' => null, ), $atts, 'iw_product_price' ); $html = ''; // 优先使用传入的ID,没有的话获取当前页面商品ID $product_id = !empty($atts['id']) ? intval($atts['id']) : (is_product() ? get_the_ID() : 0); if( $product_id > 0 && function_exists( 'wc_get_product' ) ){ $_product = wc_get_product( $product_id ); $html = $_product->get_price_html(); } return $html; } add_shortcode( 'iw_product_price', 'iw_product_price_shortcode' ); // 显示当前商品标题的短代码 [iw_product_name] function iw_product_name_shortcode( $atts ) { $atts = shortcode_atts( array( 'id' => null, ), $atts, 'iw_product_name' ); $html = ''; // 优先使用传入的ID,没有的话获取当前页面商品ID $product_id = !empty($atts['id']) ? intval($atts['id']) : (is_product() ? get_the_ID() : 0); if( $product_id > 0 && function_exists( 'wc_get_product' ) ){ $_product = wc_get_product( $product_id ); $html = $_product->get_title(); } return $html; } add_shortcode( 'iw_product_name', 'iw_product_name_shortcode' );
关键修改说明:
- 当用户没有指定
id参数时,通过is_product()判断当前是否在商品页面,再用get_the_ID()获取当前商品的ID - 保留了原有指定ID的功能,兼容之前的使用方式——你仍然可以通过
[iw_product_price id="123"]指定特定商品的价格 - 修正了短代码的
$atts第三个参数(原来的bartag是错误的,应该改为对应短代码的名称,确保短代码属性的优先级正确)
现在你只需要在商品页面直接使用[iw_product_price]和[iw_product_name],就能自动显示当前商品的价格和标题了。
内容的提问来源于stack exchange,提问作者Rifat Rahman
相关产品推荐
相关产品推荐

