Skip to content

Instantly share code, notes, and snippets.

@goranefbl
Created August 6, 2024 10:18
Show Gist options
  • Save goranefbl/44597a959d95f7e2cf37cd4e7d0b5983 to your computer and use it in GitHub Desktop.
Save goranefbl/44597a959d95f7e2cf37cd4e7d0b5983 to your computer and use it in GitHub Desktop.
Perbello auto apply coupons
<?php if (!defined('ABSPATH')) exit; // Exit if accessed directly
/**
* @param $order_get_id
* hook to thank you page referer plugin
* @@@ codja
*/
function cj_action_woocommerce_thankyou($order_get_id)
{
if (class_exists('WPGens_RAF')) {
$email_string = "Enter friend’s email";
$name_string = "Enter friend’s name";
$name_share_title = "Share your referral link with friends:";
$additional_text = get_field('rafferal_text_thnakyoupage', 'option');
$link = get_home_url();
$order = wc_get_order($order_get_id);
$email = $order->get_billing_email();
$refLink = esc_url(add_query_arg('raf', $email, trailingslashit($link)));
$message = get_option('gens_raf_myaccount_text');
$template = "<style>.gens-referral_share__email input[type='email'], .gens-referral_share__email input[type='text']{font-size:14px;}.gens-referral_share__email__title{color:#000!important;}.woocommerce-order-details,.woocommerce-customer-details{display:none;}.tom_thank_you_wrapper{margin-right:4%;margin-left:3%;padding:10px;margin-top:15px;background:#fff;border:solid 1px #e1e1e1;color:#000;} .tom_thank_you_wrapper div {direction:rtl;text-align:right;}.tom_thank_you_wrapper div p{display:block!important;}.gens-referral_share__sms{background-color:#000;color:#fff;display:none;}
@media scrren and(max-width:768px){.gens-referral_share__sms{display: block;.tom_thank_you_wrapper .gens-raf-message {padding: 20px 10px 35px 5px !important;}.tom_thank_you_wrapper .gens-raf-message .gens-ctc{display:block;bottom: 5px;text-align: right;}}}</style>";
$template .= "<div class='tom_thank_you_wrapper'><div class='gens-refer-a-friend' data-link='" . $refLink . "' data-raofz='16'>
<div class='gens-refer-a-friend--share-text' data-raofz='16'>" . $message . "</div>";
$template .= "<div class='gens-referral_share__email' data-raofz='16'>
<span class='gens-referral_share__email__title' data-raofz='16'>" . $name_share_title . "</span>
<form id='gens-referral_share__email' action='' type='post' novalidate=''>
<div class='gens-referral_share__email__inputs' data-raofz='16'>
<input type='email' placeholder='" . $email_string . "' data-raofz='16'>
<input type='text' placeholder='" . $name_string . "' data-raofz='16'>
</div>
<a href='#' id='js--gens-email-clone' data-raofz='16' role='link'>+</a>
<a href='#' id='js--gens-email-remove' data-raofz='18' role='link'>-</a>
<div style='text-align:center!important;'><input type='submit' value='" . __('Send Emails', 'gens-raf') . "' data-raofz='12'></div>";
if (!empty($additional_text)) {
$template .= "<div class='gens-refer-a-friend--share-text' data-raofz='16' style='margin:15px 0 0!important;'>" . $additional_text . "</div>";
}
$template .= "</form></div>";
$template .= "<div class='gens-raf-message gens-raf__url' data-raofz='16'>" . __("Your Referral URL:", "gens-raf") . "<strong>" . $refLink . "</strong><span class='gens-ctc' data-text='" . __("Copied!", "gens-raf") . "' data-raofz='13'>" . __("Click to copy", "gens-raf") . "</span></div>";
// $template.= "<div class='gens-referral_share' data-raofz='16'>";
// $template.= "<a href='" . $refLink . "' class='gens-referral_share__fb' data-raofz='15' role='link' aria-label='" . __("Share via Facebook","gens-raf") . "' title='" . __("Share via Facebook","gens-raf") . "'><i class='gens_raf_icn-facebook' data-raofz='15'></i>" . __("Share via Facebook","gens-raf") . "</a>";
// $template.= "<a href='" . $refLink . "' class='gens-referral_share__tw' data-via='" . __("Share via Twitter","gens-raf") . "' aria-label='" . __("Share via Twitter","gens-raf") . "' data-title='" . __("Share via Twitter","gens-raf") . "' data-raofz='15' role='link'><i class='gens_raf_icn-twitter' data-raofz='15'></i>" . __("Share via Twitter","gens-raf") . "</a>";
// $template.= "<a href='" . $refLink . "' class='gens-referral_share__wa' data-title='" . __("Share via WhatsApp","gens-raf") . "' aria-label='" . __("Share via WhatsApp","gens-raf") . "' data-raofz='15' role='link'><i class='gens_raf_icn-whatsapp' data-raofz='15'></i>" . __("Share via WhatsApp","gens-raf") . "</a>";
//// $template.= "<a href='sms:;?&body=" . $refLink . "' class='gens-referral_share__sms' data-title='" . __("Share via SMS","gens-raf") . "' aria-label='" . __("Share via SMS","gens-raf") . "' data-raofz='15' role='link'><i class='gens_raf_icn-angle-circled-up' data-raofz='15'></i>" . __("Share via SMS","gens-raf") . "</a>";
// $template.= "</div>";
$template .= "</div></div>";
echo $template;
}
}
add_action('woocommerce_thankyou', 'cj_action_woocommerce_thankyou', 10, 1);
/* AUTOMATICALLY APPLY COUPONS FROM UTM LINKS START */
add_action('wp_footer', 'wpgens_set_utm_session');
function wpgens_set_utm_session()
{
?>
<script>
(function($) {
$(document).ready(function() {
let utm_source = new URLSearchParams(window.location.search).get('utm_source');
let utm_content = new URLSearchParams(window.location.search).get('utm_content');
// Save UTM parameters to localStorage if present in the URL
if (utm_source || utm_content) {
if (utm_source) localStorage.setItem('utm_source', utm_source);
if (utm_content) localStorage.setItem('utm_content', utm_content);
} else {
// Retrieve UTM parameters from localStorage if not present in the URL
utm_source = localStorage.getItem('utm_source');
utm_content = localStorage.getItem('utm_content');
}
if (utm_source || utm_content) {
$.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'POST',
data: {
action: 'handle_utm_source',
utm_source: utm_source,
utm_content: utm_content,
nonce: '<?php echo wp_create_nonce('ajax-nonce'); ?>'
},
success: function(response) {
// Remove UTM parameters from localStorage
localStorage.removeItem('utm_source');
localStorage.removeItem('utm_content');
},
error: function(xhr, status, error) {
console.error('AJAX Error:', status, error);
}
});
}
});
})(jQuery);
</script>
<?php
}
add_action('wp_ajax_handle_utm_source', 'handle_utm_source_ajax');
add_action('wp_ajax_nopriv_handle_utm_source', 'handle_utm_source_ajax');
function handle_utm_source_ajax()
{
// Check for nonce for security
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ajax-nonce')) {
die('Nonce validation failed');
}
$utm_source = isset($_POST['utm_source']) ? sanitize_text_field($_POST['utm_source']) : '';
$utm_content = isset($_POST['utm_content']) ? sanitize_text_field($_POST['utm_content']) : '';
$coupon_code = '';
if (!empty($utm_source)) {
if (have_rows('utm_coupons', 'option')) {
while (have_rows('utm_coupons', 'option')) : the_row();
$row_source = get_sub_field('utm_source');
if (strtolower($utm_source) == strtolower($row_source)) {
$coupon_code = get_sub_field('coupon_code');
break;
}
endwhile;
}
}
if (!empty($utm_content)) {
if (have_rows('utm_content', 'option')) {
while (have_rows('utm_content', 'option')) : the_row();
$row_source = get_sub_field('utm_content');
if (strtolower($utm_content) == strtolower($row_source)) {
$coupon_code = get_sub_field('coupon_code');
break;
}
endwhile;
}
}
if (isset($coupon_code) && !empty($coupon_code)) {
if (!WC()->session->has_session()) {
WC()->session->set_customer_session_cookie(true);
}
$coupon_code_exist = WC()->session->get('coupon_code');
if (empty($coupon_code_exist)) {
WC()->session->set('coupon_code', $coupon_code);
}
}
wp_die();
}
add_action('woocommerce_add_to_cart', 'wpgens_apply_utm_coupon_to_cart', 10, 0);
function wpgens_apply_utm_coupon_to_cart()
{
// Set coupon code in session
$coupon_code = WC()->session->get('coupon_code');
if (!empty($coupon_code) && !WC()->cart->has_discount($coupon_code)) {
WC()->cart->add_discount($coupon_code);
WC()->session->__unset('coupon_code');
}
}
add_filter('woocommerce_cart_totals_coupon_label', 'wpgens_hide_coupon_code', 10, 2);
function wpgens_hide_coupon_code($text, $coupon)
{
if (method_exists($coupon, "get_code")) {
$coupon_code = $coupon->get_code();
} else {
$coupon_code = $coupon->code;
}
if (have_rows('utm_coupons', 'option')) {
while (have_rows('utm_coupons', 'option')) : the_row();
$row_coupon_code = get_sub_field('coupon_code');
if (strcasecmp($coupon_code, $row_coupon_code) == 0) { // Case-insensitive comparison
return "Coupon Applied!";
}
endwhile;
}
if (have_rows('utm_content', 'option')) {
while (have_rows('utm_content', 'option')) : the_row();
$row_coupon_code = get_sub_field('coupon_code');
if (strcasecmp($coupon_code, $row_coupon_code) == 0) { // Case-insensitive comparison
return "Coupon Applied!";
}
endwhile;
}
if (have_rows('free_products', 'option')) {
while (have_rows('free_products', 'option')) {
the_row();
$row_code = get_sub_field('coupon');
if (strcasecmp($coupon_code, $row_code) == 0) { // Case-insensitive comparison
return "Coupon Applied!";
}
}
}
return $text;
}
/* AUTOMATICALLY APPLY COUPONS FROM UTM LINKS END */
// Function to modify the order statuses checked by Referral Filter
add_filter('gens_raf_fraud_order_status', 'check_only_processing_completed_orders');
function check_only_processing_completed_orders($statuses)
{
return ['wc-processing', 'wc-completed'];
}
/**
* Customize the coupon, remove email protection and add new meta to use to list coupon on account pages.
*/
add_action('gens_after_generate_user_coupon', 'customize_coupon_meta', 10, 4);
function customize_coupon_meta($user_id, $type, $order, $coupon_id)
{
// Delete the existing customer_email meta key
delete_post_meta($coupon_id, 'customer_email');
// Get the user email from the order or user data
if ($type === 'referrer' || $type === 'registration') {
if (filter_var($user_id, FILTER_VALIDATE_EMAIL)) {
$email = $user_id;
} else {
$user_info = get_userdata($user_id);
$email = $user_info->user_email;
}
} else {
$email = (defined('WC_VERSION') && version_compare(WC_VERSION, '2.7', '<')) ? $order->billing_email : $order->get_billing_email();
}
// Add the new email meta key with the email address as the value
update_post_meta($coupon_id, 'c_email', strtolower($email));
}
add_filter('gens_raf_coupons_query', 'modify_coupon_query_args', 10, 2);
function modify_coupon_query_args($args, $user_email)
{
// Validate the user email before proceeding.
if (!filter_var($user_email, FILTER_VALIDATE_EMAIL)) {
return $args;
}
// Normalize the email to lowercase as metadata might be case-sensitive.
$normalized_email = strtolower($user_email);
// Create a meta_query that includes both potential keys.
$args['meta_query'] = array(
'relation' => 'OR', // Combine queries with 'OR' relation
array(
'key' => 'customer_email',
'value' => $normalized_email,
'compare' => 'LIKE'
),
array(
'key' => 'c_email',
'value' => $normalized_email,
'compare' => 'LIKE'
)
);
return $args;
}
/**
* Give free products per defined cart amount.
*/
function maybe_add_free_product()
{
$apply_free_product = get_option("free_product_active", 'option');
if (!$apply_free_product) {
return;
}
// Get the current cart total
$cart_total = WC()->cart->get_cart_contents_total();
// Get the repeater field data (assuming it's on an options page)
if (have_rows('free_products', 'option')) {
while (have_rows('free_products', 'option')) {
the_row();
$minimum_amount = get_sub_field('minimum_amount');
$free_product_id = get_sub_field('product');
$coupon_code = get_sub_field('coupon');
// Check if the cart total is greater than the minimum amount
if ($coupon_code) {
if (!WC()->cart->has_discount($coupon_code)) {
WC()->cart->apply_coupon($coupon_code);
}
}
if ($cart_total >= $minimum_amount) {
// if($coupon_code) {
// if (!WC()->cart->has_discount($coupon_code)) {
// WC()->cart->apply_coupon($coupon_code);
// }
// }
// Check if the free product is already in the cart
$product_in_cart = false;
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
if ($cart_item['product_id'] == $free_product_id) {
$product_in_cart = true;
break;
}
}
// Add the free product to the cart if it's not already there
if (!$product_in_cart) {
WC()->cart->add_to_cart($free_product_id, 1, 0, array(), array('is_free_product' => true));
}
} else {
// Remove the free product if it's in the cart
foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
if ($cart_item['product_id'] == $free_product_id && isset($cart_item['is_free_product']) && $cart_item['is_free_product']) {
WC()->cart->remove_cart_item($cart_item_key);
}
}
}
}
}
}
add_action('woocommerce_cart_updated', 'check_and_add_free_product_on_cart_update');
function check_and_add_free_product_on_cart_update()
{
maybe_add_free_product();
}
// Display "Free" for free products in the cart
add_filter('woocommerce_cart_item_price', 'display_free_price_cart', 20, 3);
add_filter('woocommerce_cart_item_subtotal', 'display_free_price_cart', 20, 3);
function display_free_price_cart($price, $cart_item, $cart_item_key)
{
if (isset($cart_item['is_free_product']) && $cart_item['is_free_product']) {
return '<span class="amount">Free</span>';
}
return $price;
}
// Display "Free" for free products in the checkout
add_filter('woocommerce_get_item_data', 'display_free_price_checkout', 10, 2);
function display_free_price_checkout($item_data, $cart_item)
{
if (isset($cart_item['is_free_product']) && $cart_item['is_free_product']) {
$item_data[] = [
'name' => __('Price', 'woocommerce'),
'value' => __('Free', 'woocommerce'),
];
}
return $item_data;
}
// Ensure free products don't affect the cart total
add_action('woocommerce_before_calculate_totals', 'add_custom_price', 1000, 1);
function add_custom_price($cart)
{
if (is_admin() && !defined('DOING_AJAX'))
return;
// Loop through cart items
foreach ($cart->get_cart() as $cart_item) {
if (isset($cart_item['is_free_product']) && $cart_item['is_free_product']) {
$cart_item['data']->set_price(0);
}
}
}
function wpse64458_force_recalculate_wc_totals()
{
$apply_free_product = get_option("free_product_active", 'option');
if (!$apply_free_product) {
return;
}
// Calculate totals
WC()->cart->calculate_totals();
// Save cart to session
WC()->cart->set_session();
// Maybe set cart cookies
WC()->cart->maybe_set_cart_cookies();
}
add_action('woocommerce_before_mini_cart_contents', 'wpse64458_force_recalculate_wc_totals');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment