Plugin di nostra creazione che possono essere utili.

WooCommerce Dynamic Shipping

Aggiorna le spese di spedizione al variare della nazione selezionata.

Notifica Aggiunta al carrello

Ricevi un avviso email ogniqualvolta un utente aggiunge un prodotto al carrello.

add_action('woocommerce_add_to_cart', 'send_email_on_add_to_cart');

function send_email_on_add_to_cart($cart_item_key) {
    $cart = WC()->cart->get_cart();
    $cart_item = $cart[$cart_item_key];

    $product_name = $cart_item['data']->get_name();
    $product_price = $cart_item['data']->get_price();
    $quantity = $cart_item['quantity'];

    // Email details
    $to = 'info@sitiware.it';
    $subject = 'New item added to cart';
    $headers = array('Content-Type: text/html; charset=UTF-8');
    $body = '<p>Product Name: ' . $product_name . '</p>';
    $body .= '<p>Product Price: ' . $product_price . '</p>';
    $body .= '<p>Quantity: ' . $quantity . '</p>';

    wp_mail($to, $subject, $body, $headers);
}

Aggiunta attributo title a tutte le immagini

Aggiunge l’attributo title a tutte le immagini del sito in WordPress

function add_title_attribute_to_images($content) {
    // Use regex to find all image tags
    $pattern = '/<img(.*?)>/i';

    // Callback function to process each image tag
    $content = preg_replace_callback($pattern, function($matches) {
        $img_tag = $matches[0];
        
        // Check if title attribute is already present
        if (!preg_match('/title="/i', $img_tag)) {
            // Find the `alt` attribute value
            preg_match('/alt="([^"]*)"/i', $img_tag, $alt_matches);
            $alt_text = isset($alt_matches[1]) ? $alt_matches[1] : '';

            // Add `title` attribute only if it's missing
            $img_tag = str_replace('<img', '<img title="' . esc_attr($alt_text) . '"', $img_tag);
        }

        return $img_tag;
    }, $content);

    return $content;
}
add_filter('the_content', 'add_title_attribute_to_images');
function add_title_attribute_to_images($content) {
    // Use regex to find all image tags
    $pattern = '/<img(.*?)>/i';

    // Add title attribute if it doesn't exist
    $replacement = '<img$1 title="$2"';

    // Check for `alt` attribute and duplicate it for `title`
    $content = preg_replace_callback($pattern, function($matches) {
        $img_tag = $matches[0];
        
        // Find the `alt` attribute value
        preg_match('/alt="([^"]*)"/i', $img_tag, $alt_matches);
        $alt_text = isset($alt_matches[1]) ? $alt_matches[1] : '';

        // If title attribute is missing, add it with `alt` attribute value
        if (!preg_match('/title="/i', $img_tag)) {
            $img_tag = str_replace('<img', '<img title="' . esc_attr($alt_text) . '"', $img_tag);
        }

        return $img_tag;
    }, $content);

    return $content;
}
add_filter('the_content', 'add_title_attribute_to_images');

Riattivare una subscription scaduta

Con questo snippet è possibile riattivare una subscription scaduta con lo stato di “expired”. Una volta attivato lo snippet si deve visitare il seguente url modificando iltuodoominio.com con il dominio del tuo sito e sostituendo 1234 con l’id della subscription.

https://tuodominio.com/wp-admin/admin-post.php?action=force_subscription_reactivation&subscription_id=123

add_action('admin_post_force_subscription_reactivation', 'force_subscription_reactivation');

function force_subscription_reactivation() {
    if (!current_user_can('manage_woocommerce')) {
        wp_die(__('Non hai i permessi per eseguire questa azione.', 'woocommerce'));
    }

    $subscription_id = isset($_GET['subscription_id']) ? absint($_GET['subscription_id']) : 0;

    if ($subscription_id) {
        $subscription = wcs_get_subscription($subscription_id);

        if (!$subscription) {
            wp_die(__('Subscription non trovata o ID non valido.', 'woocommerce'));
        }

        if ($subscription->has_status('expired')) {
            try {
                // Aggiorna le date obbligatorie per evitare errori
                $new_next_payment_date = gmdate('Y-m-d H:i:s', strtotime('+1 month')); // Esempio: 1 mese da oggi
                $new_end_date = gmdate('Y-m-d H:i:s', strtotime('+6 months')); // Esempio: 6 mesi da oggi

                $subscription->update_dates([
                    'next_payment' => $new_next_payment_date,
                    'end'          => $new_end_date,
                ]);

                // Aggiorna lo stato forzatamente
                wp_update_post([
                    'ID'          => $subscription_id,
                    'post_status' => 'wc-active',
                ]);

                // Salva i cambiamenti nella subscription
                $subscription->save();

                wp_redirect(admin_url('edit.php?post_type=shop_subscription'));
                exit;
            } catch (Exception $e) {
                wp_die(__('Errore durante la riattivazione della subscription: ' . $e->getMessage(), 'woocommerce'));
            }
        } else {
            wp_die(__('La subscription non è nello stato expired.', 'woocommerce'));
        }
    }

    wp_die(__('ID della subscription non valido.', 'woocommerce'));
}

Rendere dei campi di WooCommerce readonly

Con questo snippet è possibile rendere dei campi di WooCommerce nella pagina di modifica dei dati di fatturazione in modalità readonly ovvero non modificabili dall’utente.

In questo scenario vengono posti come non modificabili i campi Nome, Cognome e Codice Fiscale.

// Add this to your theme's functions.php file or a custom plugin

// Hook into WooCommerce form field rendering
add_filter('woocommerce_form_field', 'make_fields_readonly_for_wpml_specific_page', 10, 4);

function make_fields_readonly_for_wpml_specific_page($field, $key, $args, $value) {
    // Check if we are on the specific WPML page URL
    if (is_account_page() && strpos($_SERVER['REQUEST_URI'], '/it/account/edit-address/fatturazione/') !== false) {
        $readonly_fields = ['billing_first_name', 'billing_last_name', 'billing_codice_fiscale'];

        if (in_array($key, $readonly_fields)) {
            // Add readonly to the input field
            $field = str_replace('<input', '<input readonly="readonly"', $field);

            // Add a hidden field to ensure value is submitted
            $hidden_field = '<input type="hidden" name="' . esc_attr($key) . '" value="' . esc_attr($value) . '">';

            return $field . $hidden_field;
        }
    }

    return $field;
}

// Add JavaScript to handle plugin-added fields like Codice Fiscale
add_action('wp_footer', 'add_js_for_codice_fiscale_readonly_wpml');
function add_js_for_codice_fiscale_readonly_wpml() {
    // Ensure script runs only on the WPML-specific page URL
    if (is_account_page() && strpos($_SERVER['REQUEST_URI'], '/it/account/edit-address/fatturazione/') !== false) {
        ?>
        <script>
            document.addEventListener('DOMContentLoaded', function () {
                // Make Codice Fiscale field readonly
                var codiceFiscaleField = document.querySelector('#billing_codice_fiscale');
                if (codiceFiscaleField) {
                    codiceFiscaleField.setAttribute('readonly', 'readonly');

                    // Add hidden input for submission
                    var hiddenInput = document.createElement('input');
                    hiddenInput.type = 'hidden';
                    hiddenInput.name = 'billing_codice_fiscale';
                    hiddenInput.value = codiceFiscaleField.value;
                    codiceFiscaleField.parentNode.appendChild(hiddenInput);
                }
            });
        </script>
        <?php
    }
}

Reindirizzare tutti gli utenti verso una pagina dopo il login

Con questo snippet qualsiasi utente, escluso l’amministratore, viene rediretto verso una pagina specifica, in questo caso alla pagina account, spesso usata in WooCommerce.

Modifica l’url a tua discrezione nel seguente punto:

return site_url( ‘/account‘ );

function redirect_to_account_page( $redirect_to, $request, $user ) {
    // Check if the user is logged in and is a valid WP_User object
    if ( isset( $user->roles ) && is_array( $user->roles ) ) {
        // Redirect all users except administrators to the account page
        if ( ! in_array( 'administrator', $user->roles, true ) ) {
            return site_url( '/account' ); // Change '/account' to the actual slug of your account page
        }
    }

    // Default redirect
    return $redirect_to;
}
add_filter( 'login_redirect', 'redirect_to_account_page', 10, 3 );