קליטת נתונים מהקוקיז להזמנה בווקומרס

במדריך הבא נלמד כיצד ניתן לקלוט שנתונים מהURL, לשמור אותם בקוקיז של האתר ולהזין אותם אוטומטית להזמנה בווקומרס

לדוגמא: יש לנו אתר מכירות שיש כמה סוכנים המפיצים את הלינק לאתר ואנחנו רוצים למדוד רכישות לפי סוכן 
כלומר כל רכישה שהגיעה מהאתר לדעת מי הסוכן שהפיץ את הלינק לאתר.
היתרון בשימוש בקוקיז זה שהנתונים מURL נשמרים בו גם אם הגולש יצא מהעמוד ועבר לעמודים אחרים באתר או לחילופין אם הגולש סיים את הסשן בדפדפן וחזר אלין לאחר זמן.

שלב ראשון: יש להוסיף לכתובת URL את שם הפרמטר עם ערך של הסוכן
לדוגמא: www.yourdomain.com/?agent=Dani

שלב 2: נכתוב פונקציה שתאחסן את הנתון הזה בקוקיז של האתר:

				
					// Check if utm_content exists in URL parameters
if(isset($_GET['agent'])) {
    // Get the agent value
    $agent = $_GET['agent'];
    
    // Set cookie with agent value
    // Cookie will expire in 30 days (2592000 seconds)
    setcookie('agent', $agent, time() + 2592000, '/');
}

				
			

לאחר שהוספנו את הפונקציה ניכנס לקונסול בלשונית Aplication ונבדוק שהנתון אכן נשמר עם הערך שלו בcookies

שלב 3: ניצור בווקומרס שדה מותאם אליו נוכל לקלוט את הנתון מהקוקיז.
ניתן להשתמש בתוסף Checkout Field Editor for WooCommerce המאפשר להוסיף שדות להזמנה בווקומרס 
בדוגמא הבאה הוספנו שדה בשם billing_agent "שם סוכן".

שלב 4: נכתוב פונקציה אשר קולטת את הנתון מהקוקיז ומזינה אותו לשדה המיועד בווקומרס

				
					// Function to get agent value from cookie
function get_agent_from_cookie() {
    if (isset($_COOKIE['agent'])) {
        return $_COOKIE['agent'];
    }
    return ''; // Return empty if not found
}

// Auto-fill the agent field in checkout
add_filter('woocommerce_checkout_get_value', 'auto_fill_agent_code', 10, 2);
function auto_fill_agent_code($value, $field) {
    // Check if it's our custom field
    if ($field === 'billing_agent') {
        $agent_value = get_agent_from_cookie();
        if (!empty($agent_value)) {
            return $agent_value;
        }
    }
    return $value;
}

// Save the agent value to order
add_action('woocommerce_checkout_update_order_meta', 'save_agent_to_order');
function save_agent_to_order($order_id) {
    if (!empty($_POST['billing_agent'])) {
        update_post_meta($order_id, 'billing_agent', sanitize_text_field($_POST['billing_agent']));
    } else {
        // If field is empty, try to get from cookie
        $agent_value = get_agent_from_cookie();
        if (!empty($agent_value)) {
            update_post_meta($order_id, 'billing_agent', sanitize_text_field($agent_value));
        }
    }
}
				
			

בסוף התהליך יש לבצע הזמנה עם שם סוכן ב URL ולראות שזה מופיע בפרטי ההזמנה בווקומרס
לדוגמא:

ליצירת קשר השאירו פרטים כאן