如何为WooCommerce短代码输出添加商品价格与加入购物车功能
扩展WooCommerce短代码显示商品价格与加入购物车按钮
原始需求:现有WooCommerce短代码仅能以无序列表形式展示商品名称,需要为每个商品条目添加价格信息和加入购物车按钮。
修改完成的可运行代码
add_shortcode( 'product_list', 'product_list_shortcode' ); function product_list_shortcode() { $query = new WP_Query( array( 'posts_per_page' => -1, 'post_type' => 'product', 'post_status' => 'publish', 'hide_empty' => 0, 'orderby' => 'title', 'order' => 'ASC' ) ); $output = '<ul style="list-style-type:none">'; while ( $query->have_posts() ) : $query->the_post(); $product = wc_get_product( get_the_ID() ); $price = $product->get_regular_price(); $output .= '<li>' . get_the_title() . ' Price: ' . wc_price( $price ) . ' <a class="atc" href="' . $product->add_to_cart_url() . '">Add to Cart</a></li> '; endwhile; wp_reset_postdata(); return $output . '</ul>'; }
关键修改说明
- 用
WP_Query实例$query替代原循环变量,规范获取商品数据集 - 通过
wc_get_product()获取商品对象,调用get_regular_price()提取常规价格 - 借助
wc_price()自动处理价格格式化(适配站点货币符号、千位分隔符等设置) - 调用商品对象的
add_to_cart_url()生成官方标准加购链接,保障功能兼容性 - 优化产品ID和标题的获取逻辑,使用
get_the_ID()、get_the_title()更贴合WordPress开发规范 - 补充
order参数明确排序方向,消除默认排序的歧义性
内容的提问来源于stack exchange,提问作者Thomas Burrows
相关产品推荐
相关产品推荐

