包学会!WooCommerce开源电商的基础架构 - 简要介绍它的核心对象 - 有用有料

WooCommerce作为基于WordPress的开源电商插件,其核心对象构成了系统功能的基础架构。以下是其关键核心对象的简要介绍:


1. ​ WC_Product(产品类)

负责管理所有产品数据,包括基础属性(名称、价格、库存)、类型(简单产品、变量产品等)及关联分类。通过wc_get_product()函数可动态加载产品对象,支持在产品页、列表页展示及库存管理。

scss 复制代码
global $product;
// 输出别名
print_r($product);
if (have_posts()) {
    while(have_posts()) {
        the_post();

        // WC_Product_Simple 
        global $product;
        // 输出数据
        print_r($product);

        // WC_Post
        global $post;
        print_r($post);
    }
}

获取产品ID、图片和相册:

  1. 产品ID $product->get_id()
  2. 产品的图 the_post_thumbnail();
  3. 产品标题 the_title() $product->get_name()
  4. 产品价格` $product->get_regular_price();
  5. 产品简介 $product->get_short_description();
scss 复制代码
if (have_posts()) {
    while(have_posts()) {
        //
        the_post();
        // 全局变量
        global $product, $post;

        // 产品ID
        $product->get_id();
        get_the_ID();
        $post->ID;

        // 产品图片
        // shop_thumbnail 最小的尺寸
        // shop_single 用于产品详情页的大图
        // shop_catalog 列表图片
        // full 原图
        the_post_thumbnail('thumbnail');

        // 产品相册
        // 先获取图片ID
        $product->get_gallery_image_ids();
        foreach($product->get_gallery_image_ids() as $aid) {
            // 获取附件图片
            echo wp_get_attachment_image($aig, 'shop_thumbnail');
        }
    }
}

获取产品的其他常用数据:

scss 复制代码
if (have_posts()) {
    while(have_posts()) {
        the_post();
        // 全局变量
        global $product, $post;
        // 产品标题
        the_title();
        $post->post_title;
        $product->get_name();
        // 产品价格
        $product->get_price_html();
        // 产品简介
        the_excerpt();
        echo $product->get_short_description();
        // 产品货号
        echo $product->get_sku();
        // 产品正文
        the_content();
        echo $product->get_description();
        // 产品属性
        // 把全局变量传递进去
        wp_display_product_attributes($product);
        // 产品所在分类
        wc_get_product_category_list($product->get_id(), "-", "<span>", "</span>");
        // 产品所属标签
        wp_get_product_tag_list($product->get_id(), "-", "<span>", "</span>");
        // 加入购物车
        woocommerce_template_single_add_cart();
        // 增销产品 
        woocommerce_upsell_display($limit = 1, 2, $orderby, $order);
        // 相关产品
        $default = [            'posts_per_page' => 1,            'columns' => 2,            'orderby' => 'rand',            'order' => 'desc',        ];
        woocommerce_related_products($default);
    }
}

参考:WooCommerce: Get Product Data (ID, SKU, <math xmlns="http://www.w3.org/1998/Math/MathML"> ) F r o m ) From </math>)Fromproduct Object

其他:新品推荐的数据调用/ featured product 的调用:

dart 复制代码
// 在页面插入如下查询代码
$myQuery = new WP_Query([
    'post_type' => 'product',
    'posts_per_page' => -1,

    'tax_query' => [
        'relation' => 'AND',
        [
            'taxonomy' => 'product_visibility',
            'field' => 'slug',
            'terms' => [ 'exclude-from-catalog', 'outofstock' ]
            'operator' => 'NOT IN',
        ],

        [
            'taxonomy' => 'product_visibility',
            'field' => 'slug',
            'terms' => 'featured',
        ]
    ],
]);

if ($myQuery->have_posts()) {
    while($myQuery->have_posts()) {
        $myQuery->the_post();
        global $product;

        echo TT_THEME_URL;
        echo the_permalink();
        echo wc_price( wc_get_price_to_display($product, ['price' => $product->get_price(), 'qty' => 1] ) );
        echo the_post_thumbnail_url('shop_catalog');
    }
}

// 自定义查询完必须重置
wp_reset_postdata();

2. WC_Order(订单类)​

处理订单生命周期(创建、支付、发货、退款),管理订单状态(如"处理中""已完成")及关联数据(客户信息、支付方式)。存储在includes目录的class-wc-order.php中,是交易流程的核心。

参考:WooCommerce: Get Order Data (total, items, etc) From $order Object

386×203 3.93 KB

533×509 8.54 KB

3. WC_Cart(购物车类)

管理用户购物车操作,包括添加/删除商品、计算价格(含税费、运费)、生成结算数据。通过全局变量woocommerce->cart调用,依赖Session存储实时数据。

参考:WooCommerce: Get Cart Data (total, items, etc) from $cart Object

662×602 13.7 KB

cart购物车的实践使用:

初步实现ajax加入购物车:

  • 开发 AJAX 加入购物车
xml 复制代码
<script>
    console.dir(wc_add_to_cart_params);
</script>
  • 实例: 替换成我们希望的 endpoint
xml 复制代码
<script>
    // 获取 ajax 方式加入购物车的请求
    var ajax_url = wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'add_to_cart');
</script>
  • 定义返回的数据

实现指定数量的产品加入购物车:

  • jQuery 代码:
xml 复制代码
<script>

    $('#num_input').on('change', function () {
        var qty = $('#num_input').val();
        $('#add_cart').data('quantity', qty);
    });

    $('#add_cart').click(function () {

        var data = {};

        data.product_id = $('#add_cart').data('product_id');
        data.quantity = $('#add_cart').data('quantity');

        $.post(
            wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'add_to_cart'),
            data,
            function(response) {
                // TODO
                console.log(response)
            }
        );
    });

</script>

自定义ajax加购物车后的返回数据:

  • wp-content/plugins/woocommerce/includes/class-wc-ajax.php

找到 do_wc_ajax() 方法,可看见其调用了一个 add_to_cart 的钩子,然后我们再查看 add_to_cart() 方法,

再往下查看,get_refreshed_fragments() 可以看到 ajax 返回的结构。

查看源码发现,由于没有钩子可以增加返回结构,所以,我们将要扩展的数据,放入 fragments 里面。

  • functions.php
php 复制代码
// 修改默认的 ajax 加入购物车后返回的数据

add_filter('woocomerce_add_to_cart_fragments', 'tt_modify_return_data');

function tt_modify_return_data ($data) {

    $data['cart_qty'] = WC()->cart->get_cart_contents_count();

    return $data;
}
  • 再修改前端,添加到上面 JS 代码的 TODO
ini 复制代码
<script>
    if (! response) {
        return;
    }

    if (response.error && response.product_url) {
        window.location = response.product_url;
        return;
    }

    // 如果后台设置了加入购物车后跳转到购物车页面时
    if (wc_add_to_cart_params.cart_redirect_after_add === 'yes') {
        window.location = wc_add_to_cart_params.cart_url;
        return;
    }

</script>
  • 获取购物车数量

    • WC()->cart->get_cart_contents_count();

ajax动态计算指定数量的产品价格:

用户在修改购买数量时,能动态的计算总价

php 复制代码
// 自定义 AJAX 动作
function kt_calc_price() {
    // 在这里计算价格
    $data = ['total' => $p];
    wp_send_json($data);
}

add_action('wc_ajax_calc_price', 'kt_calc_price');
xml 复制代码
<script>
$('#num_input').on('change', function () {
    var qty = $(this).val();
    $('#add_cart').data('quantity', qty);
    var id = $('#add_cart').data('product_id');
    $.post(
        wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'tt_calc_price'),
        {
            count: qty,
            product_id: id,
        },
        function (response) {
            console.log(response)
        }
    );
});
</script>
  • 查看源码,发现最终会拼接成钩子 wc_ajax_tt_calc_price ,tt_calc_price 是我们传递的参数值
ini 复制代码
// 当数量改变后,计算最新总价

add_action('wc_ajax_tt_calc_price', 'tt_calc_price');

function tt_calc_price() {
    $total = 0;
    $count = $_POST['count'];
    $productId = $_POST['product_id'];

    $product = wc_get_product($productId);

    $total = wc_get_price_to_display($product, [
        'qty' => $count,
    ]);

    $total =  wc_price($total);

    wp_send_json([
        'total' => $total,
    ]);
}

4. ​WC_Customer(客户类)

存储客户信息(地址、订单历史、偏好),支持个性化服务(如基于国家自动计算运费)。可通过woocommerce->customer全局访问 。

ini 复制代码
// 获取当前客户对象
$customer = WC()->customer;

// 读取基本信息
$name = $customer->get_first_name() . ' ' . $customer->get_last_name();
$email = $customer->get_email();

// 读取地址信息
$billing_city = $customer->get_billing_city(); // 返回 "北京市"
$shipping_phone = $customer->get_shipping_phone(); // 返回 "13800138000"

// 获取完整订单历史(需客户登录)
if ($customer->get_id()) {
    $orders = wc_get_orders(['customer' => $customer->get_id()]);
}

基于地址的个性化服务

php 复制代码
// 根据客户国家自动计算运费
if ($customer->get_shipping_country() === 'US') {
    // 应用美国专属运费规则
    add_filter('woocommerce_package_rates', function($rates) {
        unset($rates['flat_rate:5']); // 移除不支持的物流方式
        return $rates;
    });
}

// 根据地区设置税率
if ($customer->get_billing_state() === 'CA') {
    // 加利福尼亚州附加税
    add_filter('woocommerce_calc_tax', function($taxes) {
        return $taxes * 1.08; // 加收8%税
    });
}

5. WooCommerce(主控类)

作为全局入口(通过$woocommerce访问),初始化其他核心对象(如WC_QueryWC_Shipping),协调支付网关、物流系统及错误处理。

WP_Query 对象概览:

自定义数据调用详解

获取要么在指定标签要么在指定分类目录 (使用 OR )

dart 复制代码
$myQuery = new WP_Query(array(
    'post_type' => 'product',
    'posts_per_page' => -1,
    'tax_query' => array(
        'relation' => 'AND',
        [
            'taxonomy' => 'product_visibility',
            'field' => 'slug',
            'terms' => ['exclude-from-catelog', 'outofstock',],
            'operator' => 'NOT IN',
        ],
        [
            'relation' => 'OR',
            [
                'taxonomy' => 'product_cat',
                'field' => 'slug',
                'terms' => 'clothing-1',
            ],
            [
                'taxonomy' => 'product_cat',
                'field' => 'slug',
                'terms' => 'beauty',
            ],
        ],
    );
));

获取所有推荐的产品

dart 复制代码
$myQuery = new WP_Query([
    'post_type' => 'product',
    'posts_per_page' => -1,
    'tax_query' => [
        'relation' => 'AND',
        [
            'taxonomy' => 'product_visibility',
            'field' => 'slug',
            'terrms' => ['exclude-from-catalog', 'outofstock'],
            'operator' => 'NOT IN',
        ],
        [
            'taxonomy' => 'product_visibility',
            'field' => 'slug',
            'terrms' => 'featured',
            'operator' => 'IN',
        ],
    ],
]);

$wpdb对象:

wpdb对象是WordPress中的一个全局对象,它是wpdb类的一个实例,用于与WordPress数据库进行交互。wpdb对象可以执行各种数据库操作,包括查询、插入、更新和删除数据等。

554×518 46.5 KB

// 执行SQL查询

<math xmlns="http://www.w3.org/1998/Math/MathML"> r e s u l t s = results = </math>results=wpdb->get_results( "SELECT * FROM {$wpdb->prefix}options WHERE option_id = 1", OBJECT );

// 获取单个变量

<math xmlns="http://www.w3.org/1998/Math/MathML"> u s e r c o u n t = user_count = </math>usercount=wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->users" );

// 获取一行数据

<math xmlns="http://www.w3.org/1998/Math/MathML"> m y l i n k = mylink = </math>mylink=wpdb->get_row( "SELECT * FROM $wpdb->links WHERE link_id = 10" );

// 获取结果集

<math xmlns="http://www.w3.org/1998/Math/MathML"> r e s u l t = result = </math>result=wpdb->get_results( "SELECT * FROM $wpdb->posts WHERE post_status = 'publish'" );


核心对象交互关系

  • 产品流程WC_Product → 用户通过WC_Cart操作 → 生成WC_Order → 关联WC_Customer数据。
  • 系统驱动WooCommerce类作为枢纽,加载并调度各模块协作。

这些对象共同构建了WooCommerce的产品管理、交易处理及用户交互能力,开发者可通过其API灵活定制功能(如扩展支付、修改购物车逻辑)。

相关推荐
绝无仅有5 分钟前
OSS文件上传解析失败,错误:文件下载失败的排查与解决
后端·面试·架构
LaoZhangAI37 分钟前
Kiro vs Cursor:2025年AI编程IDE深度对比
前端·后端
brzhang2 小时前
OpenAI 7周发布Codex,我们的数据库迁移为何要花一年?
前端·后端·架构
boyedu3 小时前
Hyperledger Fabric深入解读:企业级区块链的架构、应用与未来
架构·区块链·fabric·企业级区块链
icecreamstorm3 小时前
预处理Statement
后端
轻语呢喃3 小时前
useReducer : hook 中的响应式状态管理
javascript·后端·react.js
陈随易3 小时前
MoonBit能给前端开发带来什么好处和实际案例演示
前端·后端·程序员
Qter3 小时前
RedHat7.5运行qtcreator时出现qt.qpa.plugin: Could not load the Qt platform plugin "xcb
前端·后端
木西3 小时前
10 分钟搞定直播:Node.js + FFmpeg + flv.js 全栈实战
前端·后端·直播