基于 计算“添加到购物车”点击次数并在 WooCommerce 管理产品列表中显示它们对我上一个问题的回答,我尝试进一步修改代码以不仅包括点击次数 VS 销售量,还包括将两者相除以获得更好地了解销售情况。
这是我无法使其工作的代码:
function add_to_cart_click_counter( $product_id ) {
$product = wc_get_product( $product_id );
$count = (int) $product->get_meta( '_click_counter' );
$count++;
$product->update_meta_data( '_click_counter', $count );
$product->save();
}
add_action( 'woocommerce_add_to_cart', 'count_add_to_cart_clicks', 90, 4 );
function count_add_to_cart_clicks( $cart_item_key, $product_id, $quantity, $variation_id = null ){
if ( did_action( 'woocommerce_add_to_cart' ) === 1 ) {
add_to_cart_click_counter( $product_id );
if ( $variation_id > 0 ) {
add_to_cart_click_counter( $variation_id );
}
}
}
add_filter('manage_edit-product_columns', 'product_click_count_column' );
function product_click_count_column( $columns ) {
$columns['click_counter'] = __( 'Clicks & Sold', 'woocommerce' );
return $columns;
}
add_action( 'manage_product_posts_custom_column', 'product_click_count_column_content', 10, 2 );
function product_click_count_column_content( $column, $post_id ) {
global $product;
if ( $column === 'click_counter' ) {
if ( $product->get_type() == 'auction' ) return;
$sold_x_times = get_post_meta( $product->get_id(), 'total_sales', true );
echo '<span>Sold </span>' . $sold_x_times . '</br><span>Clicks </span>' . (int) $product->get_meta( '_click_counter' );
echo '<div style="margin-top:20px"></div>';
// everything works except the line below = what I need is statistics based on clicks / sales
// echo get_post_meta( $product->get_id(), '_click_counter' / 'total_sales', true );
}
}
用以下重新访问的代码函数替换最后一个函数:
add_action( 'manage_product_posts_custom_column', 'product_click_count_column_content', 10, 2 );
function product_click_count_column_content( $column, $post_id ) {
global $product;
if ( $column === 'click_counter' && ! $product->is_type('auction') ) {
$total_sales = (int) $product->get_total_sales();
$clicks_count = (int) $product->get_meta('_click_counter');
printf('<span>%s</span> %d<br><span>%s</span> %d', __('Sold'), $total_sales, __('Clicks'), $clicks_count);
if( $total_sales > 0 && $clicks_count > 0 ) {
printf('<div style="margin-top:8px">%s %s<div>', __('Stats'), number_format($clicks_count / $total_sales, 2));
}
}
}
代码位于子主题的functions.php 文件中(或插件中)。已测试并有效。