一、WooCommerce基础函数
WooCommerce作为WordPress最流行的电商插件,提供了丰富的函数来构建电商网站功能。
- 判断WooCommerce是否激活
if (class_exists('WooCommerce')) {
// WooCommerce已激活的代码
}
- 获取WooCommerce版本号
$wc_version = WC()->version;
- 检查当前页面是否为WooCommerce页面
if (is_woocommerce()) {
// WooCommerce页面的代码
}
二、产品相关函数
- 获取当前产品对象
global $product;
$product = wc_get_product(get_the_ID());
- 获取产品价格
$price = $product->get_price(); // 获取当前价格
$regular_price = $product->get_regular_price(); // 获取原价
$sale_price = $product->get_sale_price(); // 获取促销价
- 显示产品图片
echo $product->get_image(); // 默认大小
echo $product->get_image('shop_single'); // 指定大小
三、购物车与结算函数
- 获取购物车内容
$cart_items = WC()->cart->get_cart();
- 获取购物车总金额
$total = WC()->cart->get_total();
- 获取购物车中商品数量
$count = WC()->cart->get_cart_contents_count();
- 添加商品到购物车
WC()->cart->add_to_cart($product_id, $quantity);
四、用户账户函数
- 检查用户是否登录
if (is_user_logged_in()) {
// 用户已登录的代码
}
- 获取当前用户订单
$customer_orders = wc_get_orders(array(
'customer' => get_current_user_id(),
'limit' => 5, // 限制数量
));
- 获取用户账户菜单项
$items = wc_get_account_menu_items();
五、主题集成函数
- 移除WooCommerce默认样式
add_filter('woocommerce_enqueue_styles', '__return_empty_array');
- 添加自定义WooCommerce支持
function mytheme_add_woocommerce_support() {
add_theme_support('woocommerce');
}
add_action('after_setup_theme', 'mytheme_add_woocommerce_support');
- 修改每页显示产品数量
add_filter('loop_shop_per_page', 'new_loop_shop_per_page', 20);
function new_loop_shop_per_page($cols) {
return 12; // 修改为每页显示12个产品
}
六、钩子与过滤器
- 修改产品标题输出
add_filter('the_title', 'custom_product_title', 10, 2);
function custom_product_title($title, $id) {
if (is_shop() && get_post_type($id) === 'product') {
return '产品: ' . $title;
}
return $title;
}
- 修改价格显示格式
add_filter('woocommerce_price_format', 'custom_price_format', 10, 2);
function custom_price_format($format, $currency_pos) {
switch ($currency_pos) {
case 'left':
return '%1$s%2$s';
case 'right':
return '%2$s%1$s';
case 'left_space':
return '%1$s %2$s';
case 'right_space':
return '%2$s %1$s';
}
}
七、实用技巧
- 禁用购物车页面
add_action('template_redirect', 'redirect_cart_to_checkout');
function redirect_cart_to_checkout() {
if (is_cart()) {
wp_redirect(wc_get_checkout_url());
exit;
}
}
- 自定义添加到购物车按钮文本
add_filter('woocommerce_product_add_to_cart_text', 'custom_add_to_cart_text');
function custom_add_to_cart_text() {
return __('购买', 'woocommerce');
}
- 在产品列表显示自定义字段
add_action('woocommerce_after_shop_loop_item_title', 'display_custom_field', 5);
function display_custom_field() {
global $product;
$custom_field = get_post_meta($product->get_id(), '_custom_field', true);
if ($custom_field) {
echo '<div class="custom-field">' . esc_html($custom_field) . '</div>';
}
}
通过掌握这些常用函数,您可以更高效地开发WooCommerce主题,实现各种电商功能需求。建议在实际开发中结合官方文档使用这些函数,以确保兼容性和最佳实践。