WooCommerce的核心对象

$product对象概览 #

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. 产品价格 $rp

5. 产品简介

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');
        }
    }
}

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

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);
    }
}

$product 对象具体 :

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

  • [Product] -> [发布] -> This is a featured product
  • 推荐其实也是一种分类方式

// 在页面插入如下查询代码
$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();

$order对象概览: #

$Cart对象概览: #

cart购物车的实践使用:

初步实现ajax加入购物车:

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

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

  • jQuery 代码:
<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
// 修改默认的 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
<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动态计算指定数量的产品价格:

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


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

add_action('wc_ajax_calc_price', 'kt_calc_price');
<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 是我们传递的参数值
// 当数量改变后,计算最新总价

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,
    ]);
}

WP_Query 对象概览: #

自定义数据调用详解

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


$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',
            ],
        ],
    );
));

获取所有推荐的产品

$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对象可以执行各种数据库操作,包括查询、插入、更新和删除数据等。

// 执行SQL查询

$$results =$$wpdb->get_results( "SELECT * FROM {$wpdb->prefix}options WHERE option_id = 1", OBJECT );

// 获取单个变量

$$user_count =$$wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->users" );

// 获取一行数据

$$mylink =$$wpdb->get_row( "SELECT * FROM $wpdb->links WHERE link_id = 10" );

// 获取结果集

$$result =$$wpdb->get_results( "SELECT * FROM $wpdb->posts WHERE post_status = 'publish'" );

Powered by BetterDocs

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注