Plugin e snippet di codice 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 );

Inviare email WooCommerce ordine completato a destinatario custom in base al prodotto acquistato

Con questo snippet puoi inviare l’email di ordine completato a un indirizzo email personalizzato.

Sostituisci gli id degli ordini e l’email latuaemailcustom@email.com

add_filter('woocommerce_email_recipient_customer_completed_order', 'custom_add_admin_email_recipient', 10, 2);

function custom_add_admin_email_recipient($recipient, $order) {
    // Specify the product ID(s) you want to check
    $specific_product_ids = array(2666, 3448); // Replace with your product IDs

    // Initialize a flag to track if specific product is in the order
    $has_specific_product = false;

    // Loop through the order items
    foreach ($order->get_items() as $item) {
        $product_id = $item->get_product_id();
        if (in_array($product_id, $specific_product_ids)) {
            $has_specific_product = true;
            break;
        }
    }

    // If the order contains the specific product(s), add the additional admin email
    if ($has_specific_product) {
        $additional_email = 'latuaemailcustom@email.com'; // Replace with your desired admin email
        $recipient .= ',' . $additional_email; // Append the additional email to the admin email(s)
    }

    return $recipient;
}

Non mostrare aggiornamenti di plugin che sono già alla loro versione più recente

Con questo plugin eviti la sgradevole situazione in cui vengono mostrati plugin come da “aggiornare” mentre sono alla loro ultima e più recente versione.

Questo avviene quando lo sviluppatore del plugin aggiunge del codice che verifica se il plugin è stato attivato sul sito dello sviluppatore.

Rimuovere i prezzi da un sito WooCommerce con Rank Math SEO

Con questo snippet viene rimossa qualsiasi traccia relativa ai prezzi di un prodotto in WooCommerce in questi tre punti della pagina del prodotto:

Meta

<meta property=”product:price:amount” content=”123.66″ />

Dato strutturato generato da Rank Math

{“@type”:”Offer”,”price”:”123.99″,”priceCurrency”:”EUR”,”priceValidUntil”:”2026-12-31″ …

Tag html nella pagina

<p class=”price”><span class=”woocommerce-Price-amount amount”><bdi>123,99&nbsp;<span class=”woocommerce-Price-currencySymbol”>&euro;</span></bdi></span></p>

// Override WooCommerce product price display
add_filter('woocommerce_get_price_html', 'custom_price_message', 9999, 2);
function custom_price_message($price, $product) {
    return '<span class="custom-price-message">Contact for price</span>';
}

// Remove structured data for product price (Rank Math schema)
add_filter('rank_math/json_ld', 'remove_price_from_rank_math_schema', 9999, 2);
function remove_price_from_rank_math_schema($data, $jsonld) {
    foreach ($data as &$entry) {
        if (isset($entry['@type']) && in_array('Product', (array) $entry['@type'])) {
            if (isset($entry['offers'])) {
                unset($entry['offers']['price']);
                unset($entry['offers']['priceCurrency']);
                unset($entry['offers']['priceValidUntil']);
            }
        }
    }
    return $data;
}

// Remove meta price tag in <head>
add_action('wp_head', 'remove_price_meta_tags', 1);
function remove_price_meta_tags() {
    ob_start(function ($output) {
        // Remove <meta property="product:price:amount" ...>
        $output = preg_replace('/<meta property="product:price:amount".*?>/i', '', $output);
        $output = preg_replace('/<meta property="product:price:currency".*?>/i', '', $output);
        return $output;
    });
}

Disabilitare i commenti in WordPress

Con questo snippet i commenti vengono del tutto disabilitati negli articoli.

// Disable comments and pings
add_filter('comments_open', '__return_false', 20, 2);
add_filter('pings_open', '__return_false', 20, 2);

// Hide existing comments
add_filter('comments_array', '__return_empty_array', 10, 2);

// Remove comment support from post types
function disable_comments_post_types_support() {
    foreach (get_post_types() as $post_type) {
        if (post_type_supports($post_type, 'comments')) {
            remove_post_type_support($post_type, 'comments');
            remove_post_type_support($post_type, 'trackbacks');
        }
    }
}
add_action('admin_init', 'disable_comments_post_types_support');

Prevenire il rewrite di WPML

WPML sovrascrive il file .htaccess riscrivendo le regole degli url sia per il front end che per il backend. WPML ha rilasciato una soluzione che però non risolve in modo completo il problema. La loro soluzione è disponible qui: https://wpml.org/faq/why-is-htaccess-getting-overwritten-with-the-language-folder-on-my-wpml-website/ .

Di seguito invece lo snippet viene arricchito per intercettare anche la riscrittura degli url del backend.

add_filter('mod_rewrite_rules', 'fix_wpml_rewrites');
function fix_wpml_rewrites($rules){
    // Fix per RewriteBase
    $home_root = parse_url(home_url());
    if ( isset( $home_root['path'] ) ) {
        $home_root = trailingslashit($home_root['path']);
    } else {
        $home_root = '/';
    }

    $wpml_root = parse_url(get_option('home'));
    if ( isset( $wpml_root['path'] ) ) {
        $wpml_root = trailingslashit($wpml_root['path']);
    } else {
        $wpml_root = '/';
    }

    $rules = str_replace("RewriteBase $home_root", "RewriteBase $wpml_root", $rules);
    $rules = str_replace("RewriteRule . $home_root", "RewriteRule . $wpml_root", $rules);

    // Fix per wp-login.php
    $langs = apply_filters('wpml_active_languages', NULL, ['skip_missing' => 0]);
    if (is_array($langs)) {
        foreach ($langs as $lang_code => $lang) {
            $pattern = "RewriteRule ^$lang_code/wp-login.php /{$lang_code}/wp-login.php [QSA,L]";
            $replacement = "RewriteRule ^$lang_code/wp-login.php /wp-login.php [QSA,L]";
            $rules = str_replace($pattern, $replacement, $rules);
        }
    }

    return $rules;
}