feat(Core): add optimize and complete code
This commit is contained in:
@@ -20,6 +20,7 @@ add_action('woocommerce_before_cart', 'sodino_render_cart_banner');
|
||||
add_action('wp_enqueue_scripts', 'sodino_enqueue_banner_assets');
|
||||
add_action('wp_ajax_nopriv_sodino_banner_click', 'sodino_handle_banner_click');
|
||||
add_action('wp_ajax_sodino_banner_click', 'sodino_handle_banner_click');
|
||||
add_action('woocommerce_checkout_create_order', 'sodino_add_banner_order_meta', 20, 2);
|
||||
|
||||
function sodino_enqueue_banner_assets() {
|
||||
if (is_admin()) {
|
||||
@@ -164,12 +165,15 @@ function sodino_render_cart_banner() {
|
||||
}
|
||||
|
||||
function sodino_handle_banner_click() {
|
||||
$nonce = $_POST['nonce'] ?? ($_POST['security'] ?? '');
|
||||
$nonce = isset($_POST['nonce'])
|
||||
? sanitize_text_field(wp_unslash($_POST['nonce']))
|
||||
: (isset($_POST['security']) ? sanitize_text_field(wp_unslash($_POST['security'])) : '');
|
||||
|
||||
if (!isset($_POST['banner_id']) || !wp_verify_nonce($nonce, 'sodino_banner_click')) {
|
||||
wp_send_json_error();
|
||||
}
|
||||
|
||||
$bannerId = intval($_POST['banner_id']);
|
||||
$bannerId = absint(wp_unslash($_POST['banner_id']));
|
||||
if (!$bannerId) {
|
||||
wp_send_json_error();
|
||||
}
|
||||
@@ -180,5 +184,46 @@ function sodino_handle_banner_click() {
|
||||
}
|
||||
|
||||
$sodino_banner_service->increaseClick($bannerId);
|
||||
sodino_remember_banner_click($bannerId);
|
||||
wp_send_json_success();
|
||||
}
|
||||
|
||||
function sodino_remember_banner_click($bannerId) {
|
||||
if (!function_exists('WC') || !WC()->session) {
|
||||
return;
|
||||
}
|
||||
|
||||
$clicks = WC()->session->get('sodino_banner_clicks', []);
|
||||
if (!is_array($clicks)) {
|
||||
$clicks = [];
|
||||
}
|
||||
|
||||
$clicks[(int) $bannerId] = current_time('timestamp');
|
||||
WC()->session->set('sodino_banner_clicks', $clicks);
|
||||
}
|
||||
|
||||
function sodino_add_banner_order_meta($order, $data) {
|
||||
if (!function_exists('WC') || !WC()->session || !$order) {
|
||||
return;
|
||||
}
|
||||
|
||||
$clicks = WC()->session->get('sodino_banner_clicks', []);
|
||||
if (empty($clicks) || !is_array($clicks)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$validClicks = [];
|
||||
$cutoff = current_time('timestamp') - DAY_IN_SECONDS;
|
||||
foreach ($clicks as $bannerId => $timestamp) {
|
||||
if ((int) $bannerId > 0 && (int) $timestamp >= $cutoff) {
|
||||
$validClicks[] = (int) $bannerId;
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($validClicks)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$order->update_meta_data('_sodino_banner_click_ids', implode(',', array_values(array_unique($validClicks))));
|
||||
WC()->session->__unset('sodino_banner_clicks');
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user