Blog benéfico

Todo lo que necesitas saber sobre Charitable y nuestro equipo.

Tutorial: How to Change the Donate Button Text on a Per-Campaign Basis

Última actualización el

  • Por

While most people use Charitable for fundraising campaigns, some users have found creative uses for it. One customer recently wanted to continue using Charitable as a donation tool, while also using it as a way for people to register for their event.

The first step to achieving this is easy enough: Just create a separate campaign for the event registration. You can configure different ticket prices by using the Suggested Donations feature — simply set a price and a description.

But the challenge comes when you want to make the form button text more appropriate for the context. Instead of “Donate”, this should say something like “Purchase Tickets”.

In this tutorial, I will show you how you can use a little bit of custom code to easily customize the Donate button text on a per-campaign basis.

The Solution

To achieve this, we’re going to register a new field in the Campaign editor in the WordPress dashboard. This field will allow you to specify what the Donate button text should be.

We are also going to create modified versions of templates where the Donate button is shown; these will be stored in our theme or child theme folder and will override the default templates included in Charitable.

Step 1: Add our function

If you read my last tutorial, this step will be familiar to you.

We’re going to add a PHP function which will be run when the init hook is called within WordPress. init is a hook that happens early on while WordPress is loading, before the page has started rendering.

add_action( 'init', function() {
    // Our code will go in here.
} );

We are using an anonymous function here, which is fine as long as you are on a version of PHP greater than 5.2.

If you’re not sure how to add this to your site, check out our guide:

Step 2: Add the field to the Campaign editor

Next up, we will use the Campaign Fields API to add a “Button Text” field to the Campaign editor.

add_action( 'init', function() {

    /**
     * Create a new field as an instance of `Charitable_Campaign_Field`.
     *
     * See all available arguments at:
     *
     * @https://github.com/Charitable/Charitable/blob/ef9a468fbdd6fa83307abe6ac0c38896f625cf45/includes/fields/class-charitable-campaign-field.php
    */
    $campaign_field = new Charitable_Campaign_Field( 'button_text', array(
    'label'          => 'Button Text',
    'data_type'      => 'meta',
    'admin_form'     => array(
        'type'     => 'text',
        'required' => false,
        'default'  => 'Donate',
    ),
    'value_callback' => function( Charitable_Campaign $campaign, $key ) {
        $text = $campaign->get_meta( '_campaign_button_text' );

        // Set a default value to use when the button text is not set yet.
        if ( empty( $text ) ) {
            $text = 'Donate';
        }

        return $text;
    },
    ) );

    /**
     * Now, we register our new field.
     */
    charitable()->campaign_fields()->register_field( $campaign_field );

} );

In this code, we first of all create a new field by creating a Charitable_Campaign_Field object. We pass two parameters when creating this object:

– A key – button_text
– An array of arguments

We’re only using a sub-set of all the arguments that are possible when registering a campaign field. To see other arguments that are available, read the exhaustive inline documentation on Github.

One important argument included here is the value_callback parameter:

'value_callback' => function( Charitable_Campaign $campaign, $key ) {
    $text = $campaign->get_meta( '_campaign_button_text' );

    // Set a default value to use when the button text is not set yet.
    if ( empty( $text ) ) {
        $text = 'Donate';
    }

    return $text;
},

This is a function which will be used to get the value of the field for a particular campaign. We include it here to provide a default value of “Donate” for the button_text field; this is needed for existing campaigns that have not been saved since this campaign field was added.

If we go to add a new campaign or edit an existing one, we will now see an “Extended Settings” panel, and inside that is a “Button Text” field.

Step 3: Override the donation form template

Inside of Charitable you will see a templates directory. All templates in this directory can be overridden by creating a copy in your child theme folder. If you’re not using a child theme, you can also override them by creating a copy in your theme folder, but we recommend the child theme approach since it ensures you won’t lose your changes when updating your theme in the future.

First of all, we will create a charitable folder inside of our child theme folder. Whenever you want to override a template inside Charitable’s templates directory, it needs to be stored in the same relative location inside of the charitable folder (without templates).

In our case, we want to override the donation-form/form-donation.php template. Here’s how we do that:

  • In our child theme, we create a new file at charitable/donation-form/form-donation.php.
  • Into this, we paste the contents of the templates/donation-form/form-donation.php file in Charitable.

If you save this file and reload your donation form, you won’t notice any differences — that’s because we haven’t changed anything yet! So let’s get on to copying in our custom button text.

In the template, look for the following line:

<button class="button button-primary" type="submit" name="donate"><?php _e( 'Donate', 'charitable' ); ?></button>

In the current version of Charitable (1.6.13), this is located on line 59 but this may change in the future. The bit we need to replace is this part in the middle: <?php _e( 'Donate', 'charitable' ); ?>.

Our custom button text can be retrieved by getting the form campaign object with $form->get_campaign(), and then calling using the get( 'button_text' ) on that:

<?php echo $form->get_campaign()->get( 'button_text' ); ?>

Put together, the updated line looks like this:

<button class="button button-primary" type="submit" name="donate"><?php echo $form->get_campaign()->get( 'button_text' ); ?></button>

Now when you reload the donation form, it will show your campaign’s custom button text.

Step 4: Rinse & repeat for other templates

Step 3 fixed the donation form. But the “Donate” button appears in a couple other cases too:

  • In a list or grid of campaigns when you’re using the [campaigns] shortcode.
  • On the campaign page itself.

Determining the templates you need to override

Which templates you need to override depends on how you have set your donation form to appear with the “Display Options” setting under Charitable > Settings.

“Show on a Separate Page”

The two templates you need to override are:

  • templates/campaign/donate-button.php
  • templates/campaign-loop/donate-link.php

Copy and paste the contents of these two files into your child theme at:

  • charitable/campaign/donate-button.php
  • charitable/campaign-loop/donate-link.php

“Show on the Same Page”

The two templates you need to override are:

  • templates/campaign/donate-link.php
  • templates/campaign-loop/donate-link.php

Copy and paste the contents of these two files into your child theme at:

  • charitable/campaign/donate-link.php
  • charitable/campaign-loop/donate-link.php

“Reveal in a Modal”

The two templates you need to override are:

  • templates/campaign/donate-modal.php
  • templates/campaign-loop/donate-modal.php

Copy and paste the contents of these two files into your child theme at:

  • charitable/campaign/donate-modal.php
  • charitable/campaign-loop/donate-modal.php

Making the changes

Depending on which template you are overriding, the actual bit you need to change is either:

<?php _e( 'Donate', 'charitable' ); ?>

Or:

<?php esc_attr_e( 'Donate', 'charitable' ); ?>

To change the first variety (i.e. _e), replace it with this:

<?php echo $campaign->get( 'button_text' ); ?>

If you’re changing the second variety (i.e. esc_attr_e), swap it with this:

<?php echo esc_attr( $campaign->get( 'button_text' ) ); ?>

Wrapping up

Now that you have updated all of the templates, you should see that your custom campaign button text is used wherever a Donate button is displayed. All we had to do to get there is create a new campaign field and modify three default templates using our child theme.

If you’ve been following along, I hope you can see how the flexibility of the Campaign Fields API, this process can be used to make many more tweaks to how Charitable works on your website. For example, you could adapt this process to add a campaign-specific blurb before the donation form; it just requires creating a new campaign field and adding the value of that field to the form-donation.php template (i.e. steps 2 & 3).

Found this helpful? Any questions? I’d love to hear from you; send us an email via our Support page or leave a comment below. If you have a suggestion for a topic you would like to see me cover in a future tutorial, we’d love to hear about that, too. 🙂

Divulgación: Nuestro contenido es compatible con los lectores. Esto significa que si haces clic en algunos de nuestros enlaces, podemos ganar una comisión. Solo recomendamos productos que creemos que aportarán valor a nuestros lectores.

2 responses to “Tutorial: How to Change the Donate Button Text on a Per-Campaign Basis”

  1. Michelle Avatar
    Michelle

    On step 3, you are missing the “echo” in the second of the three code blocks. The line should read:

    get_campaign()->get( ‘button_text’ ); ?>

    1. Avatar de ericnicolaas
      ericnicolaas

      Good catch! Just fixed that up.

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Recibe consejos y recursos gratuitos directamente en tu bandeja de entrada, junto con más de 60.000 personas.

Únete a nuestro boletín

No te enviaremos spam. Solo enviamos un correo electrónico cuando creemos que realmente te ayudará. ¡Date de baja en cualquier momento!

Vídeo destacado:

Mira más vídeos en nuestro canal de YouTube.

Novedades en Benéfico

Ver las últimas actualizaciones
🔔 Suscríbete para recibir nuestras últimas actualizaciones
📧 Suscribirse a correos electrónicos

Suscripción por correo electrónico

Únete a nuestro boletín

No te enviaremos spam. Solo enviamos un correo electrónico cuando creemos que realmente te ayudará. ¡Date de baja en cualquier momento!

💂‍♂️ New DonationGuard 🛡️ Automatically Protects Your Donations!

Worried about card testing attacks or spam bots flooding your donation forms, but don’t want to ruin the giving experience for your real supporters? Charitable’s DonationGuard features:

🛡️ Real-Time Bot Detection: Actively monitors every donation submission for five distinct attack signals without slowing down your human donors.

📊 Smart Traffic Scoring: Instantly evaluates activity against a learned baseline of your site’s normal donation rhythms to catch sneaky, slow-drip card testing.

🚨 Severity-Tiered Alerts: Immediately opens structured “Attack Records” and notifies you via email and admin alerts the moment a campaign starts taking fire.

🎯 Single-Click Defense: Deploy instant security using the “Recommended Settings” preset to turn on Honeypot, Time Trap, and Rate Limit modules all at once.

🚫 Automated Blocklists: Permanently stop repeat offenders by automatically blocking suspicious email addresses based on your customized rules.

Visita esta página para obtener más información.

GiveWP Migraciones Nuevo

🧤 White Glove Migration Service for GiveWP

¿Estás pensando en cambiar tu plataforma de recaudación de fondos de GiveWP a Charitable, pero no quieres arriesgarte a perder tus datos ni a encargarte tú mismo de una configuración técnica compleja? El Servicio de Migración "White Glove" de Charitable incluye:

👥 Mapeo impecable de donantes: Transfiere de forma segura toda tu base de datos de colaboradores sin pérdida de datos.

📊 Historial financiero completo: Conserva meticulosamente cada transacción histórica para una presentación de informes continua y precisa.

🔄 Donaciones recurrentes sin interrupciones: Transfiere de forma segura las suscripciones activas sin interrumpir tus ingresos ni requerir que tus donantes actualicen su información.

💳 Cero interrupciones en la pasarela de pago: Sigue usando Stripe, PayPal o cualquier otro procesador compatible con GiveWP que ya te guste.

🚀 Configuración técnica experta: Relájate mientras nuestro equipo se encarga de la instalación y configuración de tus formularios. Además, los usuarios que cumplan los requisitos obtendrán un año completo de Charitable Pro gratis.

Visita esta página para obtener más información.

automatización Mejora

📢 Alerta de nueva función: ¡Automation Connect 2.0 ya está aquí! 🚀

¿Estás pensando en conectar tus datos de recaudación de fondos con herramientas como Mailchimp, Slack o Google Sheets, pero no quieres contratar a un desarrollador ni escribir código personalizado? El nuevo complemento de automatización de Charitable incluye:

⚡ 17 disparadores de eventos: Activa instantáneamente webhooks para el primer donativo de un donante, pagos de renovación o hitos de campaña alcanzados.

🎯 Lógica condicional inteligente: Utiliza una potente lógica AND/OR en 11 campos para enviar datos solo cuando cumplan tus criterios exactos, como las suscripciones al boletín.

📊 Control de carga útil personalizado: Selecciona entre más de 80 campos de datos limpios de metadatos de donantes, donaciones y campañas para que tus aplicaciones obtengan exactamente lo que necesitan.

🚀 Plantillas de plataforma preconstruidas: Evita la configuración desde cero con plantillas listas para usar para Zapier, Make.com, n8n, HubSpot y Slack.

🛡️ Herramientas de desarrollador fiables: Potencia tus flujos de trabajo con cargas útiles firmadas HMAC-SHA256, filtros completos de WordPress y registros de reintentos automáticos.

automatización Mejora

🔌 Charitable se une a Zapier: Conecta con más de 7000 aplicaciones y automatiza tu recaudación de fondos

¿Cansado de copiar manualmente los datos de las donaciones en hojas de contabilidad o de rastrear las nuevas suscripciones de donantes? Pon tus tareas administrativas en piloto automático. Charitable ya está oficialmente en Zapier, lo que te proporciona una forma potente y sin código para conectar tu recaudación de fondos directamente con el resto de tus herramientas favoritas.

Cada donación, suscripción de donante e hito de campaña ahora puede activar un flujo de trabajo automatizado sin problemas.

Novedades:

♾️ Conecta con más de 7000 aplicaciones: Une tus campañas de Charitable con software cotidiano como Google Sheets, QuickBooks, Slack, Mailchimp, HubSpot, Notion, Airtable y miles más.

⚡ 12 potentes disparadores: Crea flujos de trabajo profundos utilizando disparadores de automatización inteligentes que cubren todo el ciclo de vida de la donación, incluyendo Nueva Donación, Nuevo Donante, Suscripción Cancelada y Objetivo de Campaña Alcanzado.

📋 Plantillas de acciones preconstruidas: Empieza en tres minutos o menos con nuestras combinaciones de plantillas prefabricadas, como registrar automáticamente nuevas donaciones directamente en una Hoja de Cálculo de Google o enviar correos electrónicos personalizados de bienvenida a donantes a través de Gmail.

🚫 No se necesita código: No se requieren webhooks complejos ni scripts PHP personalizados. Simplemente elige tu disparador, selecciona tu aplicación, mapea tus campos y deja que Zapier se encargue del trabajo pesado.

¿Listo para ahorrar horas de tiempo administrativo? ¡Consigue Charitable Pro con el complemento Automation Connect hoy mismo y lanza tu primer Zap!

Mejora Pagos

🚀 Presentamos PayPal Commerce: Una conexión, seis formas de donar

Los donantes esperan opciones de pago modernas y flexibles cuando apoyan una causa. Si no ven su método preferido en su formulario de donación, a menudo desaparecen sin decir nada. Con PayPal Commerce, estamos brindando una experiencia de pago completamente modernizada directamente a sus campañas.

Disfrute de una única integración que mejora sus formularios, hace que las donaciones sean fluidas y le ayuda a capturar cada donación.

Novedades:

🔌 Conexión con un clic: omita las complicadas claves API y los documentos para desarrolladores. Simplemente haga clic en "Conectar con PayPal", inicie sesión en su cuenta comercial y su formulario moderno estará activo en menos de cinco minutos.

💳 Seis formas de donar: brinde a sus seguidores acceso instantáneo al saldo de PayPal, Venmo (EE. UU.), financiación "Paga más tarde", las principales tarjetas de crédito/débito, Apple Pay (Safari) y Google Pay (Chrome), todo desde el mismo formulario.

🔄 Donaciones recurrentes flexibles: admite completamente las donaciones mensuales. Elija entre la API de suscripciones de PayPal (gestionada automáticamente por PayPal) o Vault + Cron (gestionada de forma segura en su sitio).

💬 Recuperación de errores amigable: no más alertas confusas del navegador. Si se rechaza un pago, los donantes ven mensajes sencillos y en línea que los guían sobre cómo solucionar el problema y completar su donación.

¿Listo para PayPal, modernizado? Actualice a Charitable Pro 1.8.15+ (o Charitable Lite 1.8.11+) y conecte su cuenta hoy mismo.