4
25/11/2024 12:53 pm
Argomento iniziale
È possibile cambiare il ruolo di un utente dopo che ha acquistato da una specifica categoria di prodotti WooCommerce utilizzando uno snippet di codice nel file functions.php?
Grazie!
2 risposte
3
25/11/2024 12:55 pm
Utilizzare questo codice:
function change_user_role_after_category_purchase($order_id) { // Get the order object $order = wc_get_order($order_id); // Get the user ID of the customer $user_id = $order->get_user_id(); // Define the target product category $target_category = 'example-category'; // Replace with your category slug // Check if the order contains products from the target category foreach ($order->get_items() as $item_id => $item) { $product_id = $item->get_product_id(); if (has_term($target_category, 'product_cat', $product_id)) { // Change the user role $user = new WP_User($user_id); $user->set_role('new_role'); // Replace 'new_role' with your desired role slug // Exit the loop after finding a match break; } } } add_action('woocommerce_order_status_completed', 'change_user_role_after_category_purchase');
-
Sostituire i segnaposto:
- Sostituire
esempio-categoria
con lo slug della categoria di prodotto di destinazione. - Sostituire
nuovo_ruolo
con il ruolo che si vuole assegnare (ad es,abbonato
,cliente
,editore
, ecc.).
- Sostituire
-
Aggiungere il codice:
- Accedere al cruscotto dell'WordPress.
- Vai a
Aspetto > Editor dei file del tema
. - Aprire la sezione
functions.php
del tema attivo e incollare il codice in fondo.
-
Testate l'functionalità:
- Effettuare un acquisto di prova dalla categoria di destinazione e assicurarsi che il ruolo dell'utente venga aggiornato dopo che l'acquisto è stato contrassegnato come "Completato".
2
25/11/2024 12:57 pm
È inoltre possibile utilizzare il plugin Commutazione automatica dei ruoli degli utenti per WooCommerce (anche se ho avuto un conflitto con esso):
https://woocommerce.com/products/automatic-user-roles-switcher/