Files
medicalalert-web-reloaded/wp/wp-content/themes/medicalalert/functions.php
2024-10-28 14:23:22 -04:00

1693 lines
59 KiB
PHP

<?php
add_action( 'gform_after_submission_1', 'post_to_salesforce_and_five9', 10, 2 );
function post_to_salesforce_and_five9( $entry, $form ) {
post_to_salesforce( $entry, $form );
postFiveNine( $entry, $form );
}
function post_to_salesforce( $entry, $form ) {
$salesforceEnvironment = get_option('select-environment');
$Campaign_ID = $_SESSION["SESScampaignid"];
if ($salesforceEnvironment == 'full') {
$sfdc_oid = '00DDh0000009Umu';
$webtolead_url = 'https://test.salesforce.com/servlet/servlet.WebToLead';
} else {
$sfdc_oid = '00D1I000000mJ0Q';
$webtolead_url = 'https://webto.salesforce.com/servlet/servlet.WebToLead';
}
$cleanPOST = array(
'first_name' => rgar( $entry, '1.3' ),
'last_name' => rgar( $entry, '1.6' ),
'phone' => rgar( $entry, '3' ),
'email' => rgar( $entry, '4' ),
'lead_source' => 'Web',
'oid' => $sfdc_oid,
'Campaign_ID' => $Campaign_ID,
'member_status' => 'Web response',
'Inquiring_for__c' => rgar( $entry, '5' ),
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $webtolead_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($cleanPOST));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if (curl_errno($ch)) {
$error_msg = curl_error($ch);
//error_log('Salesforce Web-to-Lead Error: ' . $error_msg);
}
curl_close($ch);
}
// Function to send data to Five9
function postFiveNine( $entry, $form ) {
$Campaign_ID = '701130000026vNy';
$F9list = "Web Form Submissions H";
$F9domain = "connect america";
$permalink = getenv('HTTP_REFERER');
$title = get_permalink(url_to_postid($permalink));
date_default_timezone_set('America/New_York');
$F9Date = date("Y-m-d") . "-" . date("H:i");
$newphone = preg_replace('/^1|\D/', '', rgar($entry, '3'));
$cleanPOST = array(
'first_name' => sanitize_text_field(rgar($entry, '1.3')),
'last_name' => sanitize_text_field(rgar($entry, '1.6')),
'number1' => $newphone,
'F9domain' => $F9domain,
'F9list' => $F9list,
'salesforce_id' => $Campaign_ID,
'Device_6' => $title,
'WebDialer_Key' => $F9Date,
'F9key' => WebDialer_Key,
'F9CallASAP' => true
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.five9.com/web2campaign/AddToList");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($cleanPOST));
$response = curl_exec($ch);
if (curl_errno($ch)) {
$error_msg = curl_error($ch);
//error_log('Five9 API Error: ' . $error_msg);
}
curl_close($ch);
}
// To complete at at later date
//add_action('wp_enqueue_scripts', 'enqueue_google_maps_autocomplete');
include_once(get_template_directory() . '/helpers/SecuredContent.php');
function enqueue_google_maps_autocomplete() {
wp_enqueue_script( 'auto-complete', get_template_directory_uri().'/vendor/google/auto-complete.js');
}
// To complete at at later date
// add_action ( 'wp_head', 'googleapi' );
function googleapi(){
?>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCgGXpHzX95Ew5Da21PvSp6mEXFA78OTYQ&libraries=places&callback=initAutocomplete" ></script>
<?php
}
session_start();
# Imports all Composer packages
require __DIR__ . '/vendor/autoload.php';
use ofc\Site;
# Declare a new Site object
$site = new Site();
# Allow the Site object to be accessed in other files
function site()
{
global $site;
return $site;
}
/**
* Register Custom Navigation Walker
*/
add_action('after_setup_theme', function () {
require_once get_template_directory() . '/bootstrap_5_wp_nav_menu_walker.php';
});
register_nav_menu('consumer-menu', 'Consumer menu');
register_nav_menu('business-menu', 'Buisness menu');
register_nav_menu('col-one-consumer-menu', 'Col 1 Consumer Menu');
register_nav_menu('col-two-consumer-menu', 'Col 2 Consumer Menu');
register_nav_menu('col-three-consumer-menu', 'Col 3 Consumer Menu');
register_nav_menu('col-four-consumer-menu', 'Col 4 Consumer Menu');
register_nav_menu('col-one-business-menu', 'Col 1 Business Menu');
register_nav_menu('col-two-business-menu', 'Col 2 Business Menu');
register_nav_menu('col-three-business-menu', 'Col 3 Business Menu');
register_nav_menu('col-four-business-menu', 'Col 4 Business Menu');
/**
* Adds selected style sheet option as a class on body element
*/
add_filter('body_class', function ($class) {
$style_sheet = get_field('style_sheet');
// default to consumer brand if we don't have the ACF option for the current page
if (!$style_sheet) {
$style_sheet = "consumer-brand";
}
$class[] = $style_sheet;
return $class;
});
/**
* Creates a custom excerpt from an ACF post object
*/
function custom_excerpt($str, $length = 70, $append = '...')
{
$pieces = explode(' ', strip_tags($str));
$excerpt = implode(' ', array_slice($pieces, 0, $length));
if (count($pieces) > $length) {
$excerpt .= $append;
}
return $excerpt;
}
/**
* Replaces post excerpt truncate and sets as a link
*/
function wpdocs_excerpt_more( $more ) {
if ( ! is_single() ) {
$more = sprintf( '<a class="read-more" href="%1$s">%2$s</a>',
get_permalink( get_the_ID() ),
__( ' Read more >>', 'textdomain' )
);
}
return $more;
}
add_filter( 'excerpt_more', 'wpdocs_excerpt_more' );
/**
* WooCommerce Support
*/
add_action('after_setup_theme', function () {
add_theme_support('woocommerce');
add_theme_support('wc-product-gallery-zoom');
add_theme_support('wc-product-gallery-lightbox');
add_theme_support('wc-product-gallery-slider');
remove_action('woocommerce_before_main_content', 'woocommerce_breadcrumb', 20, 0);
/* Disable all payment gateways at checkout */
add_filter('woocommerce_cart_needs_payment', '__return_false');
// Disable different woocommerce notifications
add_filter('woocommerce_cart_item_removed_notice_type', '__return_false');
add_filter('wc_add_to_cart_message_html', '__return_false');
// when a new item gets added to the cart, empty the cart of previous items
// and purge add ons
add_filter('woocommerce_add_to_cart_validation', function ($passed, $product_id, $quantity) {
if (!WC()->cart->is_empty()) {
WC()->cart->empty_cart();
}
$_SESSION["addOns"] = [];
$_SESSION["one-time"] = [];
return $passed;
}, 20, 3);
add_filter('woocommerce_checkout_fields', function ($fields) {
return $fields;
});
});
// WooCommerce Fee Stuff
// first, wordpress doesn't use sessions, so let's enable those
add_action('init', function () {
if (!session_id()) {
session_start();
}
});
// and clean up sessions on logout
add_action('wp_logout', function () {
session_destroy();
});
// $_SESSION values are set on the cart page
add_action('woocommerce_cart_calculate_fees', function () {
$coupons_val = WC()->cart->get_applied_coupons();
$cart = WC()->cart;
$cart_contents = $cart->get_cart();
foreach ($cart_contents as $cart_item_key => $cart_item):
endforeach;
if (isset($_SESSION["Activation Fee"]) && !in_array("free-activation", $coupons_val)) {
$cartItem = null;
foreach (WC()->cart->get_cart() as $i) {
$cartItem = $i;
}
$feeLabel = get_field("fee_type", $cartItem["product_id"]);
WC()->cart->add_fee($feeLabel, $_SESSION["Activation Fee"]);
}
$attributeRatePlan = $cart_item['variation']['attribute_rate-plan'];
$keylb = $_SESSION["addOns"]["Key Lockbox"];
$onetimepo = $_SESSION['one-time'];
$proInstall = $_SESSION["one-time"];
if (isset($proInstall)) {
WC()->cart->add_fee('Professional Install', 99.00);
}
$rate_multiplier = 1;
if ($attributeRatePlan === "Semi-Annually") {
$rate_multiplier = 6;
} elseif ($attributeRatePlan === "Annually") {
$rate_multiplier = 12;
} elseif ($attributeRatePlan === "Monthly") {
$rate_multiplier = 1;
}
$cart_items = WC()->cart->get_cart_contents();
foreach ($_SESSION["addOns"] as $addOn) {
if ($attributeRatePlan === "Annually" && $addOn["label"] === "Key Lockbox") {
WC()->cart->add_fee($addOn["label"], 0);
} elseif (!isset($cart_items[$addOn["label"]])) {
WC()->cart->add_fee($addOn["label"], $addOn["price"] * $rate_multiplier);
}
}
});
/**
* Allow only one coupon per order in WooCommerce.
*/
add_filter('woocommerce_apply_individual_use_coupon', 'only_one_coupon_allowed', 10, 2);
function only_one_coupon_allowed($apply, $coupon) {
// Check if a coupon is already applied
if (WC()->cart->has_discount()) {
// Remove other applied coupons except the current one
WC()->cart->empty_discounts();
WC()->cart->apply_coupon($coupon->get_code());
return false; // Do not apply the new coupon
}
return $apply;
}
add_filter('woocommerce_add_error', 'customize_coupon_error_message', 10, 1);
function customize_coupon_error_message($error) {
// Check if the error message is related to a coupon already applied
if (strpos($error, 'Coupon code already applied!') !== false) {
return ''; // Return an empty string to suppress this specific error message
}
return $error; // Return the original error message if it's not related to coupons
}
add_action('woocommerce_cart_calculate_fees', 'add_setup_fees');
function add_setup_fees($cart) {
// Check if the cart has any coupons applied
if (empty($cart->get_applied_coupons())) {
return; // Exit if no coupons are applied
}
// Loop through each applied coupon
foreach ($cart->get_applied_coupons() as $coupon_code) {
// Get the coupon object
$coupon = new WC_Coupon($coupon_code);
// Get the coupon ID
$coupon_id = $coupon->get_id();
// Get the terms (categories) associated with this coupon
$coupon_categories = wp_get_post_terms($coupon_id, 'sc_coupon_category', array('fields' => 'ids'));
}
}
/**
* Generates a cart summary based on your current state
*
* @return string
*/
function generateCartSummary($showCheckoutButton = true) {
global $product;
WC()->session->set('chosen_shipping_methods', array( 'flat_rate:2' ) );
$shipping_methods = WC()->session->get('chosen_shipping_methods');
$cartItem = null;
foreach (WC()->cart->get_cart() as $i) {
$cartItem = $i;
}
$product = site()->getPost($cartItem["product_id"], [
"title",
"thumbnail",
"acf.activation_fee",
"acf.fee_type",
"meta._regular_price",
"shipCoupon",
"shipCouponName",
"defaultShipping",
"shippingName",
"couponList",
"couponTotal",
"activationFeeName",
"activationFeeAmount",
]);
// starting aggrigate costs
$coupon = WC()->cart->applied_coupons;
$productMonthly = $product["_regular_price"];
$oneTimeCostsFee = $product["activation_fee"]; // AKA Setup fee
$activationFeeName = $product["fee_type"];
$cart = WC()->cart;
$cart_contents = $cart->get_cart();
foreach ($cart_contents as $cart_item_key => $cart_item):
$monthlyCosts = $cart_item['data']->get_regular_price();
endforeach;
$coupons_name = WC()->cart->applied_coupons;
$prof_install_code = WC()->cart->has_discount( 'x8gt58at' );
$activation_coupon = array("l8dd","p43d","k4bu","m4jc","p584","s2bt");
$method_rate_id = 'flat_rate:2';
$shipping_type = get_title_shipping_method_from_method_id( $method_rate_id );
$cart_shipping_val= WC()->session->get('cart_totals')['shipping_total'];
$shippingPrice = (float)'29.95';
$applied_coupon = WC()->cart->get_applied_coupons();
$discount = $applied_coupon->amount;
$price_type = $addOn["price_type"];
$coupon = WC()->cart->get_coupons();
foreach ($coupon as $key => $coupon_value) {
$coupon_amount = $coupon_value->amount;
}
$s_applied_coupons = WC()->cart->get_applied_coupons();
foreach( $s_applied_coupons as $scoupon_code ){
$scoupon = new WC_Coupon($scoupon_code);
$coupon_type = $scoupon->get_discount_type();
$is_free_shipping = $scoupon->get_free_shipping();
if ($coupon_type == 'percent') {
$coupon_total = ($scoupon->amount / 100);
$coupon_subtotal = ($monthlyCosts * 12) * $coupon_total;
$samount = number_format($coupon_subtotal, 2);
$coupon_title = "Discount";
$coupon_amount = $samount;
}
if ($coupon_type == 'fixed_product') {
if ($is_free_shipping) {
$samount = (float)'29.95';
}
}
if ($coupon_type == 'fixed_cart') {
$coupon_title = "Discount";
$samount = $scoupon->amount;
}
}
// Get all coupons
$coupons = get_posts(array(
'post_type' => 'shop_coupon',
'posts_per_page' => -1,
'post_status' => 'publish',
));
// Extract post excerpt
$post_excerpt = get_the_excerpt();
// Filter coupons based on the post excerpt
$filtered_coupons = array_filter($coupons, function($coupon) {
return $coupon->post_excerpt === "Free activation";
});
// $filtered_coupons contains coupons where the post excerpt is "Free activation"
foreach( $applied_coupon as $coupon_code ){
$coupon = new WC_Coupon($coupon_code);
$freeship_coupon = $coupon->get_free_shipping();
if ($freeship_coupon) {
WC()->session->set('chosen_shipping_methods', array( 'free_shipping:4' ) );
$freeship_name = "Free Shipping";
$pro_coupon = (float)'29.95';
}
}
$proInstall = $_SESSION["one-time"];
if (isset($proInstall)) {
WC()->session->set('chosen_shipping_methods', array( 'free_shipping:4' ) );
$available_methods = WC()->shipping->packages[0]['rates'];
$shipping_method_1 = WC_Shipping_Zones::get_shipping_method(4 );
$shipping_methods = WC()->session->get('chosen_shipping_methods');
$freeship_name = "Free Shipping";
$freeship_discount = WC()->cart->get_coupon_discount_totals();
$professional_onetime = (float)'99.00';
$shipping_total = (float)'29.95';
$pro_coupon = (float)'29.95';
}
$cart = WC()->cart;
$cart_contents = $cart->get_cart();
foreach ($cart_contents as $cart_item_key => $cart_item):
endforeach;
$variable_price = $cart_item['data']->get_regular_price();
$fees = WC()->cart->get_fees();
$attributeRatePlan = $cart_item['variation']['attribute_rate-plan'];
$keylb = $_SESSION["addOns"]["Key Lockbox"];
// Separate add-ons
$fallDetection = array_filter($_SESSION["addOns"], function($item) {
return $item["label"] === "Fall Detection";
});
$protectionPlan = array_filter($_SESSION["addOns"], function($item) {
return $item["label"] === "Protection Plan";
});
$keyLockbox = array_filter($_SESSION["addOns"], function($item) {
return $item["label"] === "Key Lockbox";
});
$keyLockbox = array_filter($_SESSION["addOns"], function($item) {
return $item["label"] === "Lockbox";
});
// Store label and price in individual variables
$fallDetectionLabel = reset($fallDetection)["label"];
$fallDetectionPrice = reset($fallDetection)["price"];
$protectionPlanLabel = reset($protectionPlan)["label"];
$protectionPlanPrice = reset($protectionPlan)["price"];
$keyLockboxLabel = reset($keyLockbox)["label"];
$keyLockboxPrice = reset($keyLockbox)["price"];
if (is_iterable($_SESSION["addOns"])) {
foreach ($_SESSION["addOns"] as $addOn) {
// every addOn should have a price_type, so let's skip any oddities
if (!isset($addOn["price_type"])) {
continue;
}
}
}
if ($attributeRatePlan === "Monthly") {
$total_cart = $oneTimeCostsFee + $fallDetectionPrice + $protectionPlanPrice + $keyLockboxPrice + $monthlyCosts + $professional_onetime + $shippingPrice - $pro_coupon ;
$addon_price;
} elseif($attributeRatePlan === "Semi-Annually") {
WC()->session->set('chosen_shipping_methods', array( 'free_shipping:4' ) );
$variable_price = (float)($variable_price * 6);
$fallDetectionPrice = (float)($fallDetectionPrice * 6);
$protectionPlanPrice = (float)($protectionPlanPrice * 6);
$keyLockboxPrice = (float)($keyLockboxPrice * 6);
$available_methods = WC()->shipping->packages[0]['rates'];
$shipping_method_1 = WC_Shipping_Zones::get_shipping_method(4 );
$shipping_methods = WC()->session->get('chosen_shipping_methods');
$freeship_name = "Free Shipping";
$freeship_discount = WC()->cart->get_coupon_discount_totals();
$shipping_total = (float)'29.95';
if (isset($s_applied_coupons)) {
$sub_total = ($monthlyCosts * 6) + $oneTimeCostsFee;
$discount_subtotal = ($monthlyCosts * 6) - $samount;
$formattedDiscountTotal = number_format($discount_subtotal, 2);
$total_cart = $sub_total + $fallDetectionPrice + $protectionPlanPrice + $keyLockboxPrice + $professional_onetime - $samount;
} else {
$sub_total = ($monthlyCosts * 6) + $oneTimeCostsFee;
$total_cart = $sub_total + $fallDetectionPrice + $protectionPlanPrice + $keyLockboxPrice + $professional_onetime;
}
} elseif($attributeRatePlan === "Annually") {
$variable_price = (float)($variable_price * 12);
$protectionPlanPrice = (float)($protectionPlanPrice * 12);
$fallDetectionPrice = (float)($fallDetectionPrice * 12);
WC()->session->set('chosen_shipping_methods', array( 'free_shipping:4' ) );
$available_methods = WC()->shipping->packages[0]['rates'];
$shipping_method_1 = WC_Shipping_Zones::get_shipping_method(4 );
$shipping_methods = WC()->session->get('chosen_shipping_methods');
$freeship_name = "Free Shipping";
$freeship_discount = WC()->cart->get_coupon_discount_totals();
//$shipping_total = WC()->cart->get_shipping_total();
$shipping_total = (float)'29.95';
$free_keylockbox = "Key Lockbox";
if (isset($_SESSION['addOns']['Key Lockbox'])) {
$keyLockboxPrice = $_SESSION['addOns']['Key Lockbox']['price'] = '0.00';
}
if (isset($s_applied_coupons)) {
$sub_total = ($monthlyCosts * 12) + $oneTimeCostsFee;
$discount_subtotal = ($monthlyCosts * 12) - $samount;
$formattedDiscountTotal = number_format($discount_subtotal, 2);
$total_cart = $sub_total + $fallDetectionPrice + $protectionPlanPrice + $professional_onetime - $samount;
} else {
$sub_total = ($monthlyCosts * 12) + $oneTimeCostsFee;
$total_cart = $sub_total + $fallDetectionPrice + $protectionPlanPrice + $professional_onetime;
}
}
// addons salesforce ID
$falldetection_sfid = $_SESSION["addOns"]["Fall Detection"]["salesforce_id"];;
$protectionplan_sfid = $_SESSION["addOns"]["Protection Plan"]["salesforce_id"];
$lockbox_sfid = $_SESSION["addOns"]["Lockbox"]["salesforce_id"];
// Method to access protected property
function get_protected_property($object, $property) {
$reflection = new ReflectionClass($object);
$property = $reflection->getProperty($property);
$property->setAccessible(true);
return $property->getValue($object);
}
$rate_plan_sfid = $cart_item['variation']['attribute_rate-plan-sfid']; // Product rate plan salesforce ID
$product_id = $cart_item['product_id'];
$accessories = get_field( 'accessories', $product_id );
foreach ($accessories as $accessory) {
// Sanitize the accessory to create a valid PHP variable
$sanitized_name = strtolower(str_replace(' ', '_', $accessory["accessory_name"]));
// Assigning values to individual variables for each accessory
$accessories_name = ${$sanitized_name . '_name'} = $accessory['accessory_name'];
$accessories_sfid = ${$sanitized_name . '_salesforce_id'} = $accessory['salesforce_id'];
$accessories_price = ${$sanitized_name . '_price'} = $accessory['price'];
//var_dump($accessories_name);
//$accessories_sfid = ${$sanitized_name . '_salesforce_id'};
}
$proinstall_label = $_SESSION["one-time"]["Professional Install"]["label"];
$fees = WC()->cart->get_fees();
$applied_coupons = WC()->cart->get_applied_coupons();
foreach ($applied_coupons as $coupon_code) {
$coupon = new WC_Coupon($coupon_code);
$coupon_description = $coupon->get_description();
}
$free_activation_category = array(
'numberposts' => -1,
'post_type' => 'shop_coupon',
'orderby' => 'date',
'tax_query' => array(
array(
'taxonomy' => 'sc_coupon_category',
'field' => 'term_id',
'terms' => array(54),
),
),
);
// Get all coupons in the 'six_for_six' category (term_id = 55)
$six_for_six = array(
'numberposts' => -1,
'post_type' => 'shop_coupon',
'orderby' => 'date',
'tax_query' => array(
array(
'taxonomy' => 'sc_coupon_category',
'field' => 'term_id',
'terms' => array(55),
),
),
);
$sixforsix_category = get_posts($six_for_six);
// Get all coupons in the 'five_off' category (term_id = 56)
$five_off = array(
'numberposts' => -1,
'post_type' => 'shop_coupon',
'orderby' => 'date',
'tax_query' => array(
array(
'taxonomy' => 'sc_coupon_category',
'field' => 'term_id',
'terms' => array(56),
),
),
);
$category_coupons = get_posts($free_activation_category);
foreach ($category_coupons as $coupon) {
}
foreach ($cart->get_applied_coupons() as $coupon_code) {
$coupon = new WC_Coupon($coupon_code);
$coupon_id = $coupon->get_id();
$coupon_categories = wp_get_post_terms($coupon_id, 'sc_coupon_category', array('fields' => 'ids'));
if (in_array(55, $coupon_categories)) {
$is_sixforsix_applied = true;
}
if (in_array(56, $coupon_categories)) {
$is_fiveoff_applied = true;
}
}
if ($is_sixforsix_applied || $is_fiveoff_applied) {
$coupon_amount = $coupon->amount;
}
$cart_items = WC()->cart->get_cart();
return site()->render("cart_summary", array_merge($product, [
"variable_price" => $variable_price,
"addonPrice" => $addon_price,
"variation" => $attributeRatePlan,
"fallDetectionLabel" => $fallDetectionLabel,
"fallDetectionPrice" => $fallDetectionPrice,
"protectionPlan" => $protectionPlanLabel,
"protectionPlanprice" => $protectionPlanPrice,
"keyLockboxlabel" => $keyLockboxLabel,
"keylockboxprice" => $keyLockboxPrice,
"one-time" => $proinstall_label,
"pro-one-time" => $professional_onetime,
"couponList" => $coupon_title,
"couponTotal" => $coupon_amount,
"defaultShipping" => $shippingPrice,
"shippingName" => $shipping_type,
"shipCoupon" => $shipping_total,
"shipCouponName" => $freeship_name,
"totalMonthly" => $monthlyCosts,
"activationFeeName" => $activationFeeName,
"activationFeeAmount" => $oneTimeCostsFee,
"totalDue" => $total_cart,
"showCheckoutButton" => $showCheckoutButton,
"couponSummary" => $couponSummary,
"couponDescription" => $coupon_description,
"checkboxes" => get_field("cart_preview_checklist", "options"),
]));
}
function update_cart_prices($cart) {
foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
$product_id = $cart_item['product_id'];
$product = wc_get_product($product_id);
$variation_id = $cart_item['variation_id'];
$variation = wc_get_product($variation_id);
$variation_price = $variation->get_price();
if ($product && isset($cart_item['variation']['attribute_rate-plan'])) {
$attributeRatePlan = $cart_item['variation']['attribute_rate-plan'];
$multiplier = 1;
switch ($attributeRatePlan) {
case 'Annually':
$multiplier = 12;
break;
case 'Semi-Annually':
$multiplier = 6;
break;
case 'Monthly':
$multiplier = 1;
break;
}
$updated_price = $variation_price * $multiplier;
// Update the price in the cart item data array
$cart->cart_contents[$cart_item_key]['data']->set_price($updated_price);
}
}
}
add_action('woocommerce_before_calculate_totals', 'update_cart_prices');
function get_title_shipping_method_from_method_id( $method_rate_id = '' ){
if( ! empty( $method_rate_id ) ){
$method_key_id = str_replace( ':', '_', $method_rate_id );
$option_name = 'woocommerce_'.$method_key_id.'_settings';
return get_option( $option_name, true )['title'];
} else {
return false;
}
}
function add_administration_fees() {
WC()->cart->add_fee( 'Processing Fee', 2.5 );
}
/**
* custom woocommerce order fields
*/
$additionalWooFields = [
"subscriber_first_name" => [
"type" => "text",
"label" => "",
"placeholder" => "First Name",
"required" => true,
],
"subscriber_last_name" => [
"type" => "text",
"label" => "",
"placeholder" => "Last Name",
"required" => true,
],
"subscriber_address_1" => [
"type" => "text",
"label" => "",
"placeholder" => "Address 1",
"required" => true,
],
"subscriber_address_2" => [
"type" => "text",
"label" => "",
"placeholder" => "Address 2 (Apt, Suite, etc.)",
],
"subscriber_zip" => [
"type" => "text",
"label" => "",
"placeholder" => "Zip Code",
"required" => true,
],
"subscriber_city" => [
"type" => "text",
"label" => "",
"placeholder" => "City",
"required" => true,
],
"subscriber_state" => [
"type" => "text",
"label" => "",
"placeholder" => "State",
"required" => true,
],
"subscriber_email" => [
"type" => "text",
"label" => "",
"placeholder" => "Email Address",
],
"subscriber_phone" => [
"type" => "text",
"label" => "",
"placeholder" => "Phone Number",
],
"caregiver_relation" => [
"type" => "select",
"label" => "Relation",
"options" => [
"Brother" => "Brother",
"Daughter" => "Daughter",
"Father" => "Father",
"Friend" => "Friend",
"Granddaughter" => "Granddaughter",
"Grandson" => "Grandson",
"In-law" => "In-law",
"Mother" => "Mother",
"Neighbor" => "Neighbor",
"Relative" => "Relative",
"Sister" => "Sister",
"Son" => "Son",
"Spouse" => "Spouse",
"Other" => "Other",
],
"required" => true,
],
"caregiver_first_name" => [
"type" => "text",
"label" => "",
"placeholder" => "First Name",
"required" => true,
],
"caregiver_last_name" => [
"type" => "text",
"label" => "",
"placeholder" => "Last Name",
"required" => true,
],
"caregiver_email" => [
"type" => "text",
"label" => "",
"placeholder" => "Email Address",
],
"caregiver_phone" => [
"type" => "text",
"label" => "",
"placeholder" => "Phone Number",
],
"card_number" => [
"type" => "number",
"label" => "Credit Card",
"required" => true,
],
"ccv" => [
"type" => "number",
"label" => "CCV",
"required" => true,
],
"expiration_month" => [
"type" => "number",
"label" => "Expiration Month",
"required" => true,
"attrs" => ["min" => 1, "max" => 12, "step" => 1]
],
"expiration_year" => [
"type" => "number",
"label" => "Expiration Year",
"required" => true,
"attrs" => ["min" => 2022, "max" => 2032, "step" => 1]
],
"SESSpromoid" => [
"type" => "hidden",
"label" => "Promotion ID",
],
"SESSpromotion_description" => [
"type" => "hidden",
"label" => "Promotion Description",
],
"SESScoupon_code" => [
"type" => "hidden",
"label" => "Coupon Code",
],
];
add_action('woocommerce_before_checkout_billing_form', function ($checkout) use ($additionalWooFields) {
$dto = [];
foreach ($additionalWooFields as $key => $field) {
ob_start();
$customAttributes = ["v-model" => $key];
if ($field["attrs"]) {
$customAttributes = array_merge($customAttributes, $field["attrs"]);
}
woocommerce_form_field($key, [
'type' => $field["type"],
'class' => $field["classes"] ?? ['my-field-class orm-row-wide'],
'input_class' => $field["input_classes"] ?? [],
'label_class' => $field["label_classes"] ?? [],
'label' => $field["label"] ?? $key,
'required' => $field["placeholder"] ?? false,
'placeholder' => $field["placeholder"] ?? "",
'options' => $field["options"] ?? [],
'custom_attributes' => $customAttributes,
], $checkout->get_value($key));
$fieldHTML = ob_get_contents();
ob_end_clean();
$dto[$key] = $fieldHTML;
}
echo site()->render("checkout-step-1", $dto);
});
function showCardFields()
{
global $additionalWooFields;
$dto = [];
foreach ($additionalWooFields as $key => $field) {
if (!in_array($key, ["card_number", "ccv", "expiration_month", "expiration_year"])) {
continue;
}
ob_start();
$customAttributes = ["v-model" => $key];
if ($field["attrs"]) {
$customAttributes = array_merge($customAttributes, $field["attrs"]);
}
woocommerce_form_field($key, [
'type' => $field["type"],
'class' => $field["classes"] ?? ['my-field-class orm-row-wide'],
'input_class' => $field["input_classes"] ?? [],
'label_class' => $field["label_classes"] ?? [],
'label' => $field["label"] ?? $key,
'required' => $field["placeholder"] ?? false,
'placeholder' => $field["placeholder"] ?? "",
'options' => $field["options"] ?? [],
'custom_attributes' => $customAttributes,
], null);
$fieldHTML = ob_get_contents();
ob_end_clean();
$dto[$key] = $fieldHTML;
}
echo site()->render("card-fields", $dto);
}
add_action('woocommerce_checkout_update_order_meta', function ($orderID) use ($additionalWooFields) {
foreach ($additionalWooFields as $key => $field) {
if (isset($_POST[$key])) {
$value = esc_attr($_POST[$key]);
if ($key === "card_number") {
$parts = str_split($value);
$output = "";
for ($i = 0; $i < count($parts); $i++) {
if ($i < count($parts) - 4) {
$output .= "*";
} else {
$output .= $parts[$i];
}
}
$value = $output;
}
update_post_meta($orderID, $key, $value);
}
}
});
add_action('woocommerce_admin_order_data_after_shipping_address', function ($order) use ($additionalWooFields) {
$dto = [
"subscriber-data" => [],
"caregiver-data" => [],
];
foreach ($additionalWooFields as $key => $field) {
$meta = get_post_meta($order->get_id(), $key, true);
$dataType = (substr($key, 0, 10) === "subscriber") ? "subscriber-data" : "caregiver-data";
$dto[$dataType][] = [
"label" => $field["label"] ? $field["label"] : $field["placeholder"],
"value" => $meta ?: "",
];
}
echo site()->render("order_details_in_admin", $dto);
});
function update_individual_fields_11($entry, $form)
{
echo '</br>';
echo '</br>';
$aarpval = rgpost('input_3', true);
$aarp_val = str_replace(' ', '', $aarpval);
return $aarp_val;
global $aarp_val;
}
// AARP API
add_filter('gform_get_form_filter', 'shortcode_unautop', 11);
add_filter('gform_get_form_filter', 'do_shortcode', 11);
add_action('gform_pre_submission_7', 'aarp_api');
function aarp_api() {
$app_id = 'prodAppId';
$app_secret = 'prodSecret@123';
$aarpval = rgpost('input_3', true);
$aarp_val = str_replace(' ', '', $aarpval);
$apiUrl = 'https://selfserviceportal.lifeline.com/api/address/v1/affiliates/verify?externalIdType1=memberId&externalIdValue1=' . $aarp_val .'&affiliate=AARP';
$request = wp_remote_get($apiUrl, array('timeout' => 10, 'sslverify' => false, 'headers' => array('appId' => $app_id, 'appSecret' => $app_secret, 'Content-Type' => 'application/json')));
$body = wp_remote_retrieve_body($request);
$result = json_decode($body, true);
$memberstatus = $result["status"];
if ($memberstatus == "ACTIVE") {
add_shortcode('aarpCode', 'aarp_form');
$aarp_coupon = "E6Y8";
$_SESSION['SSESSmember']=$aarp_coupon;
} else {
add_shortcode('aarpCode', 'aarp_form_notfound');
}
}
function aarp_form()
{
$aarp_member .= '
<div class="container">
<h3> Membership Verified</h3>
<p>Thank you for providing your Member ID, your discount code will be applied to the your product selection.</p>
<p>Your discount code is:</p>
<p><b>E6Y8</b></p>
</div>
';
return $aarp_member;
global $aarp_member;
}
function aarp_form_notfound()
{
$aarp_member_notfound .= '
<div class="container">
<h3> Membership record could not be found.</h3>
<p>We could not find the AARP Membership you entered. Please re-type your number and try again. If that does not work, or you need assistance, please call our customer service team: 1-855-345-0130</p>
<p><a class="member-button text-nowrap button--primary products-list-link" href="/aarp-member-benefit">Try Again</a></p>
</div>
';
return $aarp_member_notfound;
global $aarp_member_notfound;
}
/**
* Function get_phone
*
* Get phone number from database, campaigns and google forwarding numbers
*
*/
function get_phone()
{
if (isset($_SESSION['SESScampaignphone'])) {
$num = $_SESSION["SESScampaignphone"];
$ufnum = preg_replace("/[^0-9]/", "", $num);
$fnum = substr($ufnum, 0, 3) . "-" . substr($ufnum, 3, 3) . "-" . substr($ufnum, 6);
return $fnum;
global $fnum;
} else {
$num = get_option('cta_tel', true);
$ufnum = preg_replace("/[^0-9]/", "", $num);
$fnum = substr($ufnum, 0, 3) . "-" . substr($ufnum, 3, 3) . "-" . substr($ufnum, 6);
return $fnum;
global $fnum;
}
}
add_shortcode('op', 'get_phone');
add_filter('gform_field_value_SESSpromoid', 'populate_SESSpromoid');
function populate_SESSpromoid($value) {
if (isset($_SESSION["SESSpromoid"])) {
return $_SESSION["SESSpromoid"];
} else {
return '';
};
};
add_filter('gform_field_value_SESScoupon_code', 'populate_SESScoupon_code');
function populate_SESScoupon_code($value) {
if (isset($_SESSION["SESScoupon_code"])) {
return $_SESSION["SESScoupon_code"];
} else {
return '';
};
};
add_filter('gform_field_value_SESSpromotion_description', 'populate_SESSpromotion_description');
function populate_SESSpromotion_description($value) {
if (isset($_SESSION["SESSpromotion_description"])) {
return $_SESSION["SESSpromotion_description"];
} else {
return '';
};
};
$newStatuses = [
'wc-sent-to-sales-rep' => 'Sent to Sales Rep',
'wc-test-lead' => 'Test Lead',
'wc-duplicate-lead' => 'Duplicate Lead',
];
add_action('init', function () use ($newStatuses) {
foreach ($newStatuses as $key => $label) {
register_post_status($key, [
'label' => $label,
'public' => true,
'show_in_admin_status_list' => true,
'show_in_admin_all_list' => true,
'exclude_from_search' => false,
'label_count' => _n_noop($label . ' <span class="count">(%s)</span>', $label . ' <span class="count">(%s)</span>')
]);
}
});
add_filter('wc_order_statuses', function ($order_statuses) use ($newStatuses) {
foreach ($order_statuses as $key => $status) {
$new_order_statuses[$key] = $status;
if ('wc-processing' === $key) {
foreach ($newStatuses as $key => $label) {
$new_order_statuses[$key] = $label;
}
}
}
return $new_order_statuses;
});
// auto apply the AARP coupon
add_action("woocommerce_before_checkout_form", function () {
if (isset($_SESSION["SSESSmember"]) && $_SESSION["SSESSmember"]) {
$code = strtolower($_SESSION["SSESSmember"]);
WC()->cart->apply_coupon($code);
}
if (isset($_SESSION["SESScoupon_code"]) && $_SESSION["SESScoupon_code"]) {
$couponcode = strtolower($_SESSION["SESScoupon_code"]);
if (in_array(strtolower($_SESSION["SESScoupon_code"]), WC()->cart->get_applied_coupons())) {
return;
}
WC()->cart->apply_coupon($couponcode);
}
});
add_filter( 'woocommerce_order_shipping_to_display_shipped_via', '__return_false' );
/**
* Update order emails to include all the extra stuff
*/
add_filter('woocommerce_email_order_meta_fields', function ($fields, $sent_to_admin, $order) use ($additionalWooFields) {
foreach ($additionalWooFields as $key => $value) {
$fields[$key] = [
'label' => strlen($value["label"]) ? $value["label"] : $value["placeholder"],
'value' => get_post_meta($order->get_id(), $key, true),
];
}
if (count($order->get_coupon_codes())) {
$fields["applied_coupons"] = [
"label" => "Applied Coupons",
"value" => implode(", ", $order->get_coupon_codes()),
];
}
return $fields;
}, 10, 3);
add_action('woocommerce_checkout_update_order_meta', 'save_card_details_to_order_meta');
function save_card_details_to_order_meta($order_id) {
if (isset($_POST['card_number']) && !empty($_POST['card_number'])) {
$card_number = sanitize_text_field($_POST['card_number']);
update_post_meta($order_id, '_card_number', $card_number);
$card_type = detect_card_type($card_number);
if ($card_type) {
update_post_meta($order_id, '_card_type', $card_type);
}
}
if (isset($_POST['expiration_month']) && !empty($_POST['expiration_month'])) {
$expiration_month = sanitize_text_field($_POST['expiration_month']);
update_post_meta($order_id, '_expiration_month', $expiration_month);
}
if (isset($_POST['expiration_year']) && !empty($_POST['expiration_year'])) {
$expiration_year = sanitize_text_field($_POST['expiration_year']);
update_post_meta($order_id, '_expiration_year', $expiration_year);
}
}
/**
* Function to detect card type based on the card number.
*/
function detect_card_type($number) {
$number = preg_replace('/\D/', '', $number);
$patterns = [
'Visa' => '/^4[0-9]{12}(?:[0-9]{3})?$/',
'MasterCard' => '/^5[1-5][0-9]{14}$/',
'American Express' => '/^3[47][0-9]{13}$/',
'Discover' => '/^6(?:011|5[0-9]{2})[0-9]{12}$/'
];
foreach ($patterns as $type => $pattern) {
if (preg_match($pattern, $number)) {
return $type;
}
}
return null;
}
add_action('woocommerce_thankyou', function ($order_id) {
$card_number = get_post_meta($order_id, '_card_number', true);
//error_log("Card Number: " . $card_number);
$order = wc_get_order($order_id);
$order_data = [];
foreach ($order->get_items() as $item) {
$item_data = $item->get_data();
$formatted_meta_data = $item->get_formatted_meta_data('_', true);
$order_data['items'][] = [
'name' => $item->get_name(),
'product_id' => $item->get_product_id(),
'quantity' => $item->get_quantity(),
'subtotal' => $item->get_subtotal(),
'total' => $item->get_total(),
];
}
$order_products = [];
foreach ($order->get_items() as $item) {
$product = $item->get_product();
$product_id = $product->get_id();
$product_sku = $product->get_sku();
$quantity = $item->get_quantity();
$rate_plan_id = null;
$attributes = [];
if ($product->is_type('variation')) {
$parent_id = $product->get_parent_id(); // Get the parent variable product ID
$attributes = $product->get_attributes(); // Get variation attributes
var_dump($attributes['rate-plan-sfid']);
// Get Rate Plan ID custom field for the variation
$rate_plan_id = get_post_meta($product_id, 'rate_plan_id', true); // Adjust if needed
$variation_label = implode(', ', $attributes);
} else {
// For non-variation products, still fetch Rate Plan ID if it exists
$rate_plan_id = get_post_meta($product_id, 'rate_plan_id', true);
}
}
$fees_total = 0;
foreach ($order->get_fees() as $fees) {
$order_data['fees'][] = [
'name' => $fees->get_name(),
'amount' => $fees->get_amount(),
];
$fees_total += $fees->get_amount();
}
foreach ($order->get_coupon_codes() as $coupon_code) {
$coupon = new WC_Coupon($coupon_code);
$order_data['coupons'][] = [
'code' => $coupon_code,
'discount_amount' => $coupon->get_amount(),
'remaining_usage' => ($coupon->get_usage_limit_per_user() - $coupon->get_usage_count())
];
}
// Shipping and Coupon Amount Calculation
if ($order->get_shipping_total() == 0) {
$shipping_label = 'Free Shipping';
$shipping_cost = 0;
} else {
$shipping_label = 'Shipping';
$shipping_cost = $order->get_shipping_total();
}
$order_data['shipping'] = [
'label' => $shipping_label,
'cost' => $shipping_cost
];
// Total and Subtotal Data
$order_total = (float)$order->get_total();
$order_subtotal = (float)$order->get_subtotal();
$coupon_total = (float)$order->get_discount_total();
$order_data['totals'] = [
'subtotal' => $order_subtotal,
'total' => $order_total,
'discount' => $coupon_total
];
// Send the order data to Salesforce with encryption
$request_payload = createOrderRequest($order, $card_number);
// Create a new instance of the SalesforceSync class and send the request
$sf = new SalesforceSync(SalesforceSync::kACTION_ORDER_CREATE, $request_payload);
// Send the request and log the response
$response = $sf->sendRequest();
// Log the raw response from Salesforce for debugging
//error_log('Salesforce Response (Raw): ' . print_r($response, true));
// Decode the response (assuming it is double-encoded JSON)
$decoded_response = json_decode(json_decode($response));
// Check if there are errors in the decoded response and log them
if (isset($decoded_response->ErrorList)) {
$error_response = serialize($decoded_response->ErrorList);
//error_log('Salesforce API Error: ' . $error_response);
} else {
// Log the successful response if no errors are present
//error_log('Salesforce Response (Decoded): ' . print_r($decoded_response, true));
}
// Render the order details on the thank-you page
echo site()->render("thank-you-order-details", [
"setupFeePrice" => $fees_total,
"setupFeeName" => isset($order_data['fees'][0]['name']) ? $order_data['fees'][0]['name'] : '',
"couponCode" => isset($order_data['coupons'][0]['code']) ? $order_data['coupons'][0]['code'] : '',
"couponAmount" => $coupon_total,
"monthlyFee" => $order_subtotal,
"shippingLabel" => $shipping_label,
"shippingCost" => $shipping_cost,
"freeshippingCost" => ($shipping_cost == 0) ? 'Free' : '',
"items" => array_map(function ($i) {
return [
"name" => $i['name'],
"image" => wc_get_product($i['product_id'])->get_image([100, 100]), // Get product image
];
}, $order_data['items']),
"total" => $order_total,
"fees" => $order_data['fees']
]);
});
/**
* Retrieve accessories data for a product.
*/
function getProductAccessories($product_id) {
$accessories = get_field('accessories', $product_id);
$formatted_accessories = [];
if (!empty($accessories)) {
foreach ($accessories as $accessory) {
$formatted_accessories[] = [
"AccessoryID" => $accessory['salesforce_id'],
"Quantity" => 1,
"Price" => $accessory['price']
];
}
}
return $formatted_accessories;
}
/**
* Creates the payload for the order to send to Salesforce.
*/
function createOrderRequest($order) {
// Retrieve card type from order meta
$card_type = get_post_meta($order->get_id(), '_card_type', true);
// Retrieve other payment information from the order if needed
$card_number = get_post_meta($order->get_id(), '_card_number', true);
$expiration_month = get_post_meta($order->get_id(), '_expiration_month', true);
$expiration_year = get_post_meta($order->get_id(), '_expiration_year', true);
// Create the expiration date in the required format (e.g., "MM/YYYY")
$expiration_date = sprintf('%02d/%s', $expiration_month, $expiration_year);
// Generate the request header
$header = createRequestHeader();
// Get billing and shipping information from the order
$billing = $order->get_address('billing');
$shipping = $order->get_address('shipping');
$payment_type = "Credit Card"; // Assuming credit card
// Format phone number (example: XXX-XXX-XXXX)
$billing_phone = preg_replace('/(\d{3})(\d{3})(\d{4})/', '$1-$2-$3', $billing['phone']);
$shipping_phone = !empty($shipping['phone']) ? preg_replace('/(\d{3})(\d{3})(\d{4})/', '$1-$2-$3', $shipping['phone']) : $billing_phone;
// Prepare product items and accessories
$order_products = [];
foreach ($order->get_items() as $item) {
$product = $item->get_product(); // Get the WC_Product object
$product_id = $product->get_id();
$product_sku = $product->get_sku();
$quantity = $item->get_quantity();
$rate_plan_id = null;
$attributes = [];
$parent_id = $product->get_parent_id(); // Get the parent variable product ID
$attributes = $product->get_attributes(); // Get variation attributes
// Get Rate Plan ID custom field for the variation
$rate_plan_id = get_post_meta($product_id, 'rate_plan_id', true);
// Include additional variation details
$variation_label = implode(', ', $attributes);
// Fetch accessories related to this product
$accessories = getProductAccessories($item->get_product_id());
//error_log( print_r($accessories, true) );
// Add variation or product details to the order products array
$order_products[] = [
'ProductID' => $product_sku,
'Quantity' => $item->get_quantity(),
'RatePlanID' => $attributes['rate-plan-sfid'],
'Accessories' => $accessories,
'PromotionID' => $promotion_id
];
}
// Create the payload structure
$orderRequest = [
"RequestHeader" => $header,
"RequestBody" => [
"CustomerFirstName" => $billing['first_name'],
"CustomerLastName" => $billing['last_name'],
"CustomerEmail" => $billing['email'],
"CustomerPhoneNumber" => $billing_phone,
"GCLID" => "",
"UserExperience" => null,
"CustomField1" => "",
"CustomField2" => "",
"CustomField3" => "",
"CustomField4" => "",
"MarketingCampaign" => "ecom campaign",
"ShippingID" => "a4t3s000000pYVVAA2",
"PaymentInformation" => [
"PaymentType" => $payment_type,
"CardholderName" => $billing['first_name'] . ' ' . $billing['last_name'],
"CardType" => $card_type,
"CardNumber" => $card_number,
"ExpirationDate" => $expiration_date
],
"ShippingInformation" => [
"FirstName" => $shipping['first_name'],
"LastName" => $shipping['last_name'],
"Phone" => $shipping_phone,
"Street1" => $shipping['address_1'],
"Street2" => $shipping['address_2'],
"City" => $shipping['city'],
"State" => $shipping['state'],
"PostalCode" => $shipping['postcode'],
"Country" => $shipping['country'] == 'US' ? 'United States' : $shipping['country']
],
"BillingInformation" => [
"FirstName" => $billing['first_name'],
"LastName" => $billing['last_name'],
"Phone" => $billing_phone,
"Street1" => $billing['address_1'],
"Street2" => $billing['address_2'],
"City" => $billing['city'],
"State" => $billing['state'],
"PostalCode" => $billing['postcode'],
"Country" => $billing['country'] == 'US' ? 'United States' : $billing['country']
],
"OrderProducts" => $order_products
],
];
return $orderRequest;
}
/**
* Creates a request header with a unique ID.
*/
function createRequestHeader() {
return [
"RequestID" => "Request_" . microtime(true)
];
}
if (!class_exists("SalesforceSync")) {
class SalesforceSync {
const kACTION_ORDER_CREATE = "CreateOrder";
const kAPPEND_URL = "?brand=MedicalAlert";
private $url;
private $content;
private $method;
public function __construct($action, $content, $method = "POST") {
// Appending ?brand=MedicalAlert to the URL
$environment_url = get_option('id_api_salesforce', true);
$this->url = "{$environment_url}/{$action}" . self::kAPPEND_URL;
$this->content = $content;
$this->method = $method;
}
public function sendRequest() {
$crypto = new SecuredContent();
$encoded_content = json_encode($crypto->encode_content(json_encode($this->content)));
$request = curl_init($this->url);
curl_setopt($request, CURLOPT_CUSTOMREQUEST, $this->method);
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
curl_setopt($request, CURLOPT_POSTFIELDS, $encoded_content);
curl_setopt($request, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($encoded_content),
]);
// Execute the request and retrieve the response
$response = curl_exec($request);
curl_close($request);
// Decode the encrypted response
return $crypto->decode_content($response);
}
}
}
/**
* Rewrite WordPress URLs to Include /blog/ in Post Permalink Structure
*
* @author Golden Oak Web Design <info@goldenoakwebdesign.com>
* @license https://www.gnu.org/licenses/gpl-2.0.html GPLv2+
*/
function blog_generate_rewrite_rules( $wp_rewrite ) {
$new_rules = array(
'(([^/]+/)*blog)/page/?([0-9]{1,})/?$' => 'index.php?pagename=$matches[1]&paged=$matches[3]',
'blog/([^/]+)/?$' => 'index.php?post_type=post&name=$matches[1]',
'blog/[^/]+/attachment/([^/]+)/?$' => 'index.php?post_type=post&attachment=$matches[1]',
'blog/[^/]+/attachment/([^/]+)/trackback/?$' => 'index.php?post_type=post&attachment=$matches[1]&tb=1',
'blog/[^/]+/attachment/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=post&attachment=$matches[1]&feed=$matches[2]',
'blog/[^/]+/attachment/([^/]+)/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=post&attachment=$matches[1]&feed=$matches[2]',
'blog/[^/]+/attachment/([^/]+)/comment-page-([0-9]{1,})/?$' => 'index.php?post_type=post&attachment=$matches[1]&cpage=$matches[2]',
'blog/[^/]+/attachment/([^/]+)/embed/?$' => 'index.php?post_type=post&attachment=$matches[1]&embed=true',
'blog/[^/]+/embed/([^/]+)/?$' => 'index.php?post_type=post&attachment=$matches[1]&embed=true',
'blog/([^/]+)/embed/?$' => 'index.php?post_type=post&name=$matches[1]&embed=true',
'blog/[^/]+/([^/]+)/embed/?$' => 'index.php?post_type=post&attachment=$matches[1]&embed=true',
'blog/([^/]+)/trackback/?$' => 'index.php?post_type=post&name=$matches[1]&tb=1',
'blog/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=post&name=$matches[1]&feed=$matches[2]',
'blog/([^/]+)/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=post&name=$matches[1]&feed=$matches[2]',
'blog/page/([0-9]{1,})/?$' => 'index.php?post_type=post&paged=$matches[1]',
'blog/[^/]+/page/?([0-9]{1,})/?$' => 'index.php?post_type=post&name=$matches[1]&paged=$matches[2]',
'blog/([^/]+)/page/?([0-9]{1,})/?$' => 'index.php?post_type=post&name=$matches[1]&paged=$matches[2]',
'blog/([^/]+)/comment-page-([0-9]{1,})/?$' => 'index.php?post_type=post&name=$matches[1]&cpage=$matches[2]',
'blog/([^/]+)(/[0-9]+)?/?$' => 'index.php?post_type=post&name=$matches[1]&page=$matches[2]',
'blog/[^/]+/([^/]+)/?$' => 'index.php?post_type=post&attachment=$matches[1]',
'blog/[^/]+/([^/]+)/trackback/?$' => 'index.php?post_type=post&attachment=$matches[1]&tb=1',
'blog/[^/]+/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=post&attachment=$matches[1]&feed=$matches[2]',
'blog/[^/]+/([^/]+)/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?post_type=post&attachment=$matches[1]&feed=$matches[2]',
'blog/[^/]+/([^/]+)/comment-page-([0-9]{1,})/?$' => 'index.php?post_type=post&attachment=$matches[1]&cpage=$matches[2]',
);
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
add_action( 'generate_rewrite_rules', 'blog_generate_rewrite_rules' );
function update_post_link( $post_link, $id = 0 ) {
$post = get_post( $id );
if( is_object( $post ) && $post->post_type == 'post' ) {
return home_url( '/blog/' . $post->post_name . '/');
}
return $post_link;
}
add_filter( 'post_link', 'update_post_link', 1, 3 );
function skip_redirect( $skip_redirect, $post_id, $post ) {
if ( $post->post_type === 'post' ) {
$skip_redirect = true;
}
return $skip_redirect;
}
add_filter( 'wpseo_premium_post_redirect_slug_change', 'skip_redirect', 10, 3 );
// Google Tag Manager
add_action( 'wp_head', 'gtm_output', 2 );
add_action( 'wp_footer', 'gtm_datalayer_init', 10 );
add_action( 'body_top', 'gtm_noscript_output' );
function gtm_output() { ?>
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-MJH5WQQ');</script>
<!-- End Google Tag Manager -->
<?php
}
function gtm_noscript_output() { ?>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-MJH5WQQ"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
<?php
}
function gtm_datalayer_init() {?>
<script>window.dataLayer = window.dataLayer || [];</script>
<?php
}
add_action( 'wp_footer', 'refresh_cart');
function refresh_cart() { ?>
<script>
(function ( $ ) {
$( document ).ready( function () {
$( document.body ).on( 'applied_coupon_in_checkout removed_coupon_in_checkout', function () {
location.reload();
} );
} );
})( jQuery );
</script>
<?php
}
// Ensure only one item in the cart
add_filter('woocommerce_add_cart_item_data', 'restrict_cart_to_one_item', 10, 3);
function restrict_cart_to_one_item($cart_item_data, $product_id, $variation_id) {
global $woocommerce;
if (!$woocommerce->cart->is_empty()) {
unset($_SESSION["one-time"]);
unset($_SESSION["addOns"]);
$woocommerce->cart->empty_cart();
}
return $cart_item_data;
}
add_filter('woocommerce_checkout_fields', 'customize_billing_fields');
function customize_billing_fields($fields) {
unset($fields['billing']['billing_company']);
$fields['billing']['billing_first_name']['label'] = '';
$fields['billing']['billing_last_name']['label'] = '';
$fields['billing']['billing_address_1']['label'] = '';
$fields['billing']['billing_address_2']['label'] = '';
$fields['billing']['billing_city']['label'] = '';
$fields['billing']['billing_postcode']['label'] = '';
$fields['billing']['billing_phone']['label'] = '';
$fields['billing']['billing_email']['label'] = '';
$fields['billing']['billing_state']['label'] = '';
$fields['billing']['billing_state']['placeholder'] = 'Select Your State';
$fields['billing']['billing_first_name']['placeholder'] = __('First Name', 'woocommerce');
$fields['billing']['billing_last_name']['placeholder'] = __('Last Name', 'woocommerce');
$fields['billing']['billing_address_1']['placeholder'] = __('Street address', 'woocommerce');
$fields['billing']['billing_address_2']['placeholder'] = __('Apartment, suite, unit etc. (optional)', 'woocommerce');
$fields['billing']['billing_city']['placeholder'] = __('City', 'woocommerce');
$fields['billing']['billing_postcode']['placeholder'] = __('Postcode / ZIP', 'woocommerce');
$fields['billing']['billing_phone']['placeholder'] = __('Phone', 'woocommerce');
$fields['billing']['billing_email']['placeholder'] = __('Email address', 'woocommerce');
return $fields;
}
add_action('woocommerce_init', 'woocommerce_shipping_instances_form_fields_filters');
function woocommerce_shipping_instances_form_fields_filters(){
foreach( WC()->shipping->get_shipping_methods() as $shipping_method ) {
add_filter('woocommerce_shipping_instance_form_fields_' . $shipping_method->id, 'shipping_methods_additional_custom_field');
}
}
function shipping_methods_additional_custom_field( $settings ) {
$settings['shipping_comment'] = array(
'title' => __('Salesforce ID', 'woocommerce'),
'type' => 'text',
'placeholder' => __( 'Enter any additional comments for this shipping method.', 'woocommerce' ),
);
return $settings;
}