Skip to content

Instantly share code, notes, and snippets.

@Acephalia
Created April 20, 2023 23:56
Show Gist options
  • Select an option

  • Save Acephalia/4878dc453484dbd3b222bbf6a6ad896f to your computer and use it in GitHub Desktop.

Select an option

Save Acephalia/4878dc453484dbd3b222bbf6a6ad896f to your computer and use it in GitHub Desktop.
Stop checkout and log order to text file.
//This code will fail the checkout process with a custom message. The order time and products that were attemtpted to be purchased will be logged to a text file in wp/content and the log will be displayed under Checkout Log in the wordpress Dashboard.
// Add custom admin page
add_action('admin_menu', 'auto_fail_custom_admin_page');
function auto_fail_custom_admin_page() {
add_menu_page(
'Checkout Log',
'Checkout Log',
'manage_options',
'checkout-log',
'auto_fail_custom_admin_page_callback'
);
}
function auto_fail_custom_admin_page_callback() {
$file_path = WP_CONTENT_DIR . '/checkout_log.txt';
if (file_exists($file_path)) {
$log_data = file_get_contents($file_path);
$log_data = explode("\n", trim($log_data));
} else {
$log_data = array();
file_put_contents($file_path, '');
}
?>
<div class="wrap">
<h1>Checkout Log</h1>
<ol>
<?php foreach ($log_data as $log_entry) : ?>
<li><?php echo esc_html($log_entry); ?></li>
<?php endforeach; ?>
</ol>
</div>
<?php
}
// Add checkout error message
add_action('woocommerce_checkout_process', 'auto_fail_custom_checkout_error');
function auto_fail_custom_checkout_error() {
//change customer notice here
wc_add_notice(__('Sorry, you cannot purchase this item yet.'), 'error');
}
// Log checkout attempts
add_action('woocommerce_before_checkout_form', 'auto_fail_custom_checkout_logging');
function auto_fail_custom_checkout_logging() {
// Get the current timestamp
$timestamp = current_time('mysql');
// Get the cart items
$cart_items = WC()->cart->get_cart();
// Get the product names
$product_names = array();
foreach ($cart_items as $cart_item) {
$product = $cart_item['data'];
$product_name = $product->get_name();
$product_names[] = $product_name;
}
$product_names = implode(',', $product_names);
// Save the timestamp and product names to a text file
$file_path = WP_CONTENT_DIR . '/checkout_log.txt';
if (!file_exists($file_path)) {
// Create the file if it doesn't exist
file_put_contents($file_path, '');
}
$log_entry = sprintf('%s - %s', $timestamp, $product_names);
$log_data = file_get_contents($file_path);
$log_data .= $log_entry . "\n";
file_put_contents($file_path, $log_data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment