Last active
April 18, 2025 20:04
-
-
Save StefsterNYC/7975931a5b853beb7df3ba8a4c09d77b to your computer and use it in GitHub Desktop.
Adds a Counter Log in the WP-Content Folder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @snippet Adds an ATC Counter | |
* @author Serafin Tech | |
* @compatible WooCommerce 7+ | |
* @website https://serafintech.io | |
*/ | |
add_action('woocommerce_add_to_cart', 'track_atc_with_total', 10, 6); | |
function track_atc_with_total($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) { | |
$user_id = get_current_user_id(); | |
$ip = $_SERVER['REMOTE_ADDR']; | |
$time = current_time('mysql'); | |
$product = wc_get_product($product_id); | |
$product_name = $product ? $product->get_name() : 'Unknown'; | |
$log_file = WP_CONTENT_DIR . '/atc-log.log'; | |
$counter_file = WP_CONTENT_DIR . '/atc-counter.json'; | |
// Load or initialize counter data | |
$counters = file_exists($counter_file) ? json_decode(file_get_contents($counter_file), true) : []; | |
// Update counter | |
if (!isset($counters[$product_id])) { | |
$counters[$product_id] = 0; | |
} | |
$counters[$product_id] += $quantity; | |
// Save updated counters | |
file_put_contents($counter_file, json_encode($counters), LOCK_EX); | |
// Log line with total clicks | |
$total = $counters[$product_id]; | |
$log_line = "[{$time}] User ID: {$user_id} | IP: {$ip} | Product ID: {$product_id} | Product: {$product_name} | Qty: {$quantity} | Total Clicked: {$total}\n"; | |
file_put_contents($log_file, $log_line, FILE_APPEND | LOCK_EX); | |
} | |
// These will be your results in the log file | |
//[2025-04-18 15:55:35] User ID: 1 | IP: ************ | Product ID: 238 | Product: Beanie | Qty: 1 | Total Clicked: 1 | |
//[2025-04-18 15:56:03] User ID: 1 | IP: ************ | Product ID: 17 | Product: Album | Qty: 1 | Total Clicked: 1 | |
//[2025-04-18 15:56:47] User ID: 1 | IP: ************ | Product ID: 238 | Product: Beanie | Qty: 1 | Total Clicked: 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment