You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 00:55:27