Contactar con el servicio de asistencia

Atención al cliente 24 horas al día, 7 días a la semana

Todos los sistemas operativos

Tienda en línea siempre abierta

Cómo bloquear fácilmente enlaces en Gravity Forms: Guía paso a paso

Cómo bloquear fácilmente enlaces en Gravity Forms: Guía paso a paso

Facebook
Twitter
LinkedIn
Pinterest
🕒 4 minutos 9 segundos | 👁️ 10310 | 👤 10306 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. Go to Plugins → Add New in your WordPress salpicadero.
  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. Go to Snippets → Add New in your WordPress salpicadero.
  2. Give your snippet a descriptive name, like: “Block URLs in Gravity Form 9”.
  3. Paste the code into the editor.
  4. Elija 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.

Reflexiones finales

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

Using the 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 o 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. 🚀



¿Necesita ayuda con su proyecto? Póngase en contacto con nosotros.

Llámanos al: 00302310729873
Envíenos un mensaje a: [email protected]
Rellene nuestro Formulario de contacto

Foto de Constantinos Albanidis

Constantinos Albanidis

Somos Pioneros en el Campo del Marketing, creando soluciones personalizadas e innovadoras para ayudar a nuestros clientes a hacer crecer sus negocios y alcanzar sus objetivos.

Síguenos

Suscríbase a nuestro canal

Acerca de Freespirits

En FreeSpirits Web Services, creemos que su presencia en línea debe reflejar la singularidad y el espíritu de su negocio. Nuestro equipo de diseñadores y desarrolladores expertos se dedica a crear sitios web visualmente impresionantes y fáciles de usar que capten la esencia de su marca. Desde diseños web cautivadores hasta funcionalidad sin fisuras, ofrecemos servicios web integrales adaptados a sus necesidades específicas. Tanto si se trata de un pequeño negocio como de una gran empresa, nuestra experiencia en diseño y desarrollo web garantiza que su sitio web destaque entre los demás, atraiga a los visitantes e impulse los resultados. Experimente la libertad de un sitio web bellamente diseñado que realmente encarna el espíritu de su negocio con FreeSpirits Web Services.

Últimos artículos

Suscríbase a nuestro
Canal griego

Angelina
¿Cómo puedo ayudar?
Angelina
Angelina
×
Angelina
¡Hola! Estoy aquí para ayudarte. Pregúntame cualquier cosa sobre nuestro negocio, nuestros servicios o productos.
×
es_ES
small_c_popup.png
Embudo de boletines de afiliación

Únase a nosotros para dar forma al futuro del marketing.

Inscríbase en el formulario del boletín de noticias que aparece a continuación para recibir las últimas noticias y actualizaciones sobre increíbles herramientas y oportunidades de marketing.