在 Woocommerce 管理优惠券编辑页面上显示自定义数据 [英] Display custom data on Woocommerce admin coupon edit pages
问题描述
对于我在系统中定义的每张优惠券,我想显示使用统计信息:使用了多少销售额,提供了多少折扣等...我想在该优惠券的编辑页面上添加该数据在管理员中(作为新标签或元框)
For every coupon I have defined in the system I would like to show usage statistics: how much sales it was used with, how much discount it provided, etc... I would like to add that data on that coupon's edit page in the admin (either as a new tab or a metabox)
所以我有代码来计算使用该优惠券的所有销售额.但是如何将其添加到 woocommerce admin 中的优惠券编辑页面
So I have the code to count all sales used that coupon. But how do I add it to the coupon edit page in woocommerce admin
function get_sales_by_coupon($coupon_id) {
$args = [
'post_type' => 'shop_order',
'posts_per_page' => '-1',
'post_status' => ['wc-processing', 'wc-completed']
];
$my_query = new WP_Query($args);
$orders = $my_query->posts;
$total = 0;
foreach ($orders as $key => $value) {
$order_id = $value->ID;
$order = wc_get_order($order_id);
$items = $order->get_items('coupon');
foreach ( $items as $item ) {
if( $item['code'] == $coupon_id ) {
$total += $order->get_total();
}
}
}
return 'Total sales for coupon "' . $coupon_id . '": ' . wc_price($total);
}
推荐答案
你得到的订单越多,你的函数就会越繁重……相反,直接创建一个轻量级的 SQL 查询会更好指定优惠券代码的订单总数.
The more orders you will get, more your function is going to be heavy… Instead it will be much better to make a direct lighter SQL query that will get the sum of orders totals for a defined coupon code.
然后在优惠券编辑页面上使用自定义的侧边元框,您将能够显示:
Then using a custom side metabox on coupon edit pages, you will be able to display that:
// Get totals orders sum for a coupon code
function get_total_sales_by_coupon( $coupon_code ) {
global $wpdb;
return (float) $wpdb->get_var( $wpdb->prepare("
SELECT SUM( pm.meta_value )
FROM {$wpdb->prefix}postmeta pm
INNER JOIN {$wpdb->prefix}posts p
ON pm.post_id = p.ID
INNER JOIN {$wpdb->prefix}woocommerce_order_items woi
ON woi.order_id = pm.post_id
WHERE pm.meta_key = '_order_total'
AND p.post_status IN ('wc-processing','wc-completed')
AND woi.order_item_name LIKE '%s'
AND woi.order_item_type = 'coupon'
", $coupon_code ) );
}
// Adding Meta container to admin shop_coupon pages
add_action( 'add_meta_boxes', 'add_custom_coupon_meta_box' );
if ( ! function_exists( 'add_custom_coupon_meta_box' ) )
{
function add_custom_coupon_meta_box()
{
add_meta_box( 'coupon_usage_data', __('Usage data','woocommerce'), 'custom_coupon_meta_box_content', 'shop_coupon', 'side', 'core' );
}
}
// Displaying content in the meta container on admin shop_coupon pages
if ( ! function_exists( 'custom_coupon_meta_box_content' ) )
{
function custom_coupon_meta_box_content() {
global $post;
$total = get_total_sales_by_coupon( $post->post_title );
printf( __("Total sales: %s"), wc_price( $total ) );
}
}
代码位于活动子主题(或活动主题)的 functions.php 文件中.经测试有效.
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
这篇关于在 Woocommerce 管理优惠券编辑页面上显示自定义数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!