Blog caritatif

Tout ce que vous devez savoir sur Charitable et notre équipe.

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

Dernière mise à jour le

  • Par

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.

La 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. 🙂

Divulgation : Notre contenu est soutenu par nos lecteurs. Cela signifie que si vous cliquez sur certains de nos liens, nous pouvons gagner une commission. Nous ne recommandons que les produits qui, selon nous, ajouteront de la valeur à nos lecteurs.

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 ericnicolaas
      ericnicolaas

      Good catch! Just fixed that up.

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont marqués d'une *

Recevez des conseils et des ressources gratuits directement dans votre boîte de réception, ainsi que 60 000 autres personnes

Rejoignez notre newsletter

Nous ne vous enverrons pas de spam. Nous envoyons un e-mail uniquement lorsque nous pensons qu'il vous sera réellement utile. Désabonnez-vous à tout moment !

Vidéo en vedette :

Regardez plus de vidéos sur notre chaîne YouTube.

Quoi de neuf dans Charitable

Voir les dernières mises à jour
🔔 Abonnez-vous pour recevoir nos dernières mises à jour
📧 Abonnez-vous aux e-mails

Abonnement par e-mail

Rejoignez notre newsletter

Nous ne vous enverrons pas de spam. Nous envoyons un e-mail uniquement lorsque nous pensons qu'il vous sera réellement utile. Désabonnez-vous à tout moment !

💂‍♂️ 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.

Visitez cette page pour en savoir plus.

GiveWP Migrations Nouveau

🧤 White Glove Migration Service for GiveWP

Vous envisagez de passer de GiveWP à Charitable pour votre plateforme de collecte de fonds, mais vous ne voulez pas risquer de perdre vos données ni gérer vous-même une configuration technique complexe ? Le service de migration "White Glove" de Charitable comprend :

👥 Cartographie parfaite des donateurs : transférez en toute sécurité toute votre base de données de supporters sans aucune perte de données.

📊 Historique financier complet : préservez méticuleusement chaque transaction historique pour des rapports continus et précis.

🔄 Dons récurrents transparents : transférez en toute sécurité les abonnements récurrents actifs sans perturber vos revenus entrants ni obliger vos donateurs à mettre à jour leurs informations.

💳 Aucune interruption de passerelle : continuez à utiliser Stripe, PayPal ou tout autre processeur compatible avec GiveWP que vous utilisez déjà.

🚀 Configuration technique experte : détendez-vous pendant que notre équipe s'occupe du travail le plus difficile pour installer et configurer vos formulaires — de plus, les utilisateurs éligibles reçoivent une année complète de Charitable Pro gratuitement.

Visitez cette page pour en savoir plus.

automatisation Amélioration

📢 Alerte nouvelle fonctionnalité : Automation Connect 2.0 est là ! 🚀

Vous envisagez de connecter vos données de collecte de fonds à des outils comme Mailchimp, Slack ou Google Sheets, mais vous ne voulez pas engager un développeur ou écrire du code personnalisé ? Le nouvel add-on d'automatisation de Charitable propose :

⚡ 17 déclencheurs d'événements : déclenchez instantanément des webhooks pour le premier don d'un donateur, les paiements de renouvellement ou les étapes importantes de la campagne atteintes.

🎯 Logique conditionnelle intelligente : utilisez une logique ET/OU puissante sur 11 champs pour n'envoyer des données que lorsqu'elles répondent à vos critères exacts, comme les inscriptions à la newsletter.

📊 Contrôle personnalisé de la charge utile : choisissez parmi plus de 80 champs de données propres sur les métadonnées du donateur, du don et de la campagne afin que vos applications obtiennent exactement ce dont elles ont besoin.

🚀 Modèles de plateforme pré-intégrés : évitez la configuration à partir de zéro avec des modèles prêts à l'emploi pour Zapier, Make.com, n8n, HubSpot et Slack.

🛡️ Outils de développement fiables : alimentez vos flux de travail avec des charges utiles signées HMAC-SHA256, des filtres WordPress complets et des journaux de nouvelles tentatives automatiques.

automatisation Amélioration

🔌 Charitable rencontre Zapier : Connectez-vous à plus de 7 000 applications et automatisez votre collecte de fonds

Fatigué de copier manuellement les données de dons dans des feuilles comptables ou de rechercher les nouvelles inscriptions de donateurs ? Mettez vos tâches administratives en pilote automatique. Charitable est maintenant officiellement sur Zapier, vous offrant un moyen puissant et sans code de connecter directement votre collecte de fonds au reste de vos outils préférés.

Chaque don, inscription de donateur et jalon de campagne peut désormais déclencher un flux de travail automatisé en toute transparence.

Quoi de neuf :

♾️ Connectez-vous à plus de 7 000 applications : Reliez vos campagnes Charitable à des logiciels quotidiens comme Google Sheets, QuickBooks, Slack, Mailchimp, HubSpot, Notion, Airtable, et des milliers d'autres.

⚡ 12 déclencheurs puissants : Créez des flux de travail approfondis à l'aide de déclencheurs d'automatisation intelligents couvrant l'ensemble du cycle de vie des dons, y compris Nouveau don, Nouveau donateur, Abonnement annulé et Objectif de campagne atteint.

📋 Modèles d'actions pré-intégrés : Commencez en trois minutes ou moins avec nos combinaisons de modèles prédéfinis, comme l'enregistrement automatique des nouveaux dons directement dans une feuille Google ou l'envoi d'e-mails de bienvenue personnalisés aux donateurs via Gmail.

🚫 Zéro code requis : Pas de webhooks complexes ni de scripts PHP personnalisés nécessaires. Choisissez simplement votre déclencheur, sélectionnez votre application, mappez vos champs, et laissez Zapier s'occuper du travail acharné.

Prêt à économiser des heures d'administration ? Obtenez Charitable Pro avec le module complémentaire Automation Connect dès aujourd'hui et lancez votre premier Zap !

Amélioration Paiements

🚀 Présentation de PayPal Commerce : Une connexion, six façons de faire un don

Les donateurs s'attendent à des options de paiement modernes et flexibles lorsqu'ils soutiennent une cause. S'ils ne voient pas leur méthode préférée sur votre formulaire de don, ils disparaissent souvent sans un mot. Avec PayPal Commerce, nous apportons une expérience de paiement entièrement modernisée directement à vos campagnes.

Profitez d'une seule intégration qui améliore vos formulaires, rend le don transparent et vous aide à capturer chaque don.

Quoi de neuf :

🔌 Connexion en un clic : Oubliez les clés API compliquées et la documentation pour développeurs. Cliquez simplement sur « Se connecter avec PayPal », connectez-vous à votre compte professionnel, et votre formulaire moderne sera en ligne en moins de cinq minutes.

💳 Six façons de donner : Offrez à vos supporters un accès instantané à leur solde PayPal, Venmo (US), le financement « Pay Later », les principales cartes de crédit/débit, Apple Pay (Safari) et Google Pay (Chrome), le tout à partir du même formulaire.

🔄 Dons récurrents flexibles : Prend entièrement en charge les dons mensuels. Choisissez entre l'API PayPal Subscriptions (gérée automatiquement par PayPal) ou Vault + Cron (gérée en toute sécurité sur votre site).

💬 Récupération d'erreurs conviviale : Fini les alertes navigateur confuses. Si un paiement est refusé, les donateurs voient des messages clairs et intégrés qui les guident sur la façon de résoudre le problème et de finaliser leur don.

Prêt pour PayPal, modernisé ? Mettez à jour vers Charitable Pro 1.8.15+ (ou Charitable Lite 1.8.11+) et connectez votre compte dès aujourd'hui !