Contacter le support technique

Assistance à la clientèle 24 heures sur 24, 7 jours sur 7

+30 6974 319 263

Parlez à un vrai technicien maintenant.

Tous les systèmes sont opérationnels

La boutique en ligne est toujours ouverte

How to Easily Block Links in Gravity Forms: Step-by-Step Guide

How to Easily Block Links in Gravity Forms: Step-by-Step Guide

Facebook
Twitter
LinkedIn
Pinterest
🕒 4 minutes 9 secondes | 👁️ 10524 | 👤 10520 visits | 📊 100%

Gravity Forms is one of the most powerful form builders for WordPress.
It’s flexible, feature-rich, and integrates seamlessly with countless plugins.
But like any form system, it can be misused.

One common issue WordPress site owners face is users submitting unwanted links or URLs inside form fields. These links can clutter your database, introduce spam, and in some cases even pose a security risk.

Fortunately, with just one small snippet of code, you can completely block links from being submitted into your Gravity Forms fields—while still allowing users to enter their email addresses.

In this guide, you’ll learn step by step how to:

  • Install and use the Code Snippets plugin.
  • Add a custom function that prevents URLs from being submitted.
  • Apply the validation to a specific form and exclude the email field.
  • Keep your forms clean, safe, and professional.

Why Block Links in Gravity Forms?

There are several reasons you may want to stop links from being submitted into your Gravity Forms:

  1. Spam Prevention – Bots and spammers often drop links in forms hoping to promote their websites.
  2. Clean Data Collection – If you’re collecting feedback, surveys, or customer input, you don’t want messy URLs cluttering up your entries.
  3. Security Hardening – Some links can redirect to malicious sites, creating unnecessary risk for your team or clients reviewing submissions.
  4. Professionalism – Preventing links ensures only relevant content is entered, keeping your data consistent and trustworthy.

The Tool You’ll Need: Code Snippets Plugin

Instead of editing your theme’s functions.php file (which is risky and gets reset when you update your theme), you can use the Code Snippets plugin.

Code Snippets is a free plugin that lets you safely add custom PHP code to your WordPress site without touching core files. It provides:

  • A clean interface for adding snippets.
  • The ability to enable/disable snippets without losing them.
  • No need for a child theme.

👉 To install it:

  1. Aller à Plugins → Add New in your WordPress tableau de bord.
  2. Search for Code Snippets.
  3. Install and activate it.

Now you’re ready to add your custom code.

The Snippet Code to Block Links in Gravity Forms

Here’s the exact snippet you’ll need. It works on Form ID 9, and blocks links in every field except the Email field (ID 2).

// Block URLs in ANY field of form ID 9 except the Email field (ID 2)
add_filter( 'gform_field_validation_9', 'block_urls_except_email', 10, 4 );
function block_urls_except_email( $result, $value, $form, $field ) {

    // Skip validation for Email field
    if ( $field->id == 2 ) {
        return $result;
    }

    $nourl_pattern = '/https?://|www.|[a-z0-9-]+.[a-z]{2,}/i';

    // Recursive function to check arrays for URLs
    $contains_url = function($val) use ($nourl_pattern, &$contains_url) {
        if ( is_array($val) ) {
            foreach ($val as $v) {
                if ($contains_url($v)) return true;
            }
            return false;
        }
        return is_string($val) && preg_match($nourl_pattern, $val);
    };

    if ( $contains_url($value) ) {
        $result['is_valid'] = false;
        $result['message']  = 'Message cannot contain website addresses.';
    }

    return $result;
}

How This Code Works

Let’s break it down:

add_filter( ‘gform_field_validation_9’, … )
This tells Gravity Forms to run our custom validation function on form ID 9.

if ( $field->id == 2 )
This ensures the Email field (ID 2) is excluded, so users can still submit email addresses.

$nourl_pattern
This regular expression (regex) checks for any pattern that looks like a URL (http, https, www, or domain extensions like .com, .org, etc.).

$contains_url
A recursive function that checks arrays or strings to detect any URLs.

$result[‘is_valid’] = false;
If a link is detected, the field will fail validation, and the user will see the error message.

$result[‘message’] = ‘Message cannot contain website addresses.’;
This is the error message displayed when someone tries to submit a link.

Step-by-Step: Adding the Snippet

  1. Aller à Snippets → Add New in your WordPress tableau de bord.
  2. Give your snippet a descriptive name, like: “Block URLs in Gravity Form 9”.
  3. Paste the code into the editor.
  4. Choose Only run on site front-end (important for form submissions).
  5. Save and activate the snippet.

That’s it! 🎉 Your form is now protected.

Testing Your Gravity Form

  • Try submitting your form with a normal text response → ✅ It should work.
  • Try adding a URL like http://example.com → ❌ It should trigger the validation error.
  • Try entering an email address in the email field → ✅ It should still allow it.

This ensures your form only accepts clean, useful input.

Réflexions finales

Blocking links in Gravity Forms fields is a smart way to protect your website from spam, keep your entries clean, and improve security.

L'utilisation de la Code Snippets plugin makes it easy to manage this code without editing your theme files. And the snippet provided here is flexible—you can modify the Form ID ou excluded field IDs to fit your needs.

👉 Now your Gravity Forms are safer, smarter, and more professional.

If you found this guide helpful, don’t forget to Like, Share, and Subscribe to our content for more WordPress tutorials, tips, and snippets. 🚀



Besoin d'aide pour votre projet ? Prenez contact avec nous !

Appelez-nous : 00302310729873
Envoyez-nous un message : [email protected]
Remplir notre Formulaire de contact

Image de Constantinos Albanidis

Constantinos Albanidis

Pionniers dans le domaine du marketing, nous créons des solutions personnalisées et innovantes pour aider nos clients à développer leurs activités et à atteindre leurs objectifs.

Suivez-nous

S'abonner à notre chaîne

À propos de Freespirits

Chez FreeSpirits Web Services, nous pensons que votre présence en ligne doit refléter le caractère unique et l'esprit de votre entreprise. Notre équipe de concepteurs et de développeurs qualifiés se consacre à la création de sites web visuellement étonnants et conviviaux qui capturent l'essence de votre marque. Des conceptions captivantes aux fonctionnalités transparentes, nous fournissons des services web complets adaptés à vos besoins spécifiques. Que vous soyez une petite ou une grande entreprise, notre expertise en matière de conception et de développement de sites web vous garantit que votre site web se démarque de la masse, qu'il attire les visiteurs et qu'il génère des résultats. Découvrez la liberté d'un site web magnifiquement conçu qui incarne véritablement l'esprit de votre entreprise avec FreeSpirits Web Services.

Derniers articles

S'abonner à notre
Chaîne grecque

×
fr_FR
small_c_popup.png
Entonnoir de la lettre d'information de l'affilié

Rejoignez-nous pour façonner l'avenir du marketing !

Inscrivez-vous à la lettre d'information ci-dessous pour recevoir toutes les dernières nouvelles et mises à jour sur les outils de marketing et les opportunités extraordinaires.