Blog caritatif

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

Tutorial: How to Add Campaign-Specific Content to the Donation Receipt Email

Dernière mise à jour le

  • Par

If you run many campaigns, you may need to add campaign-specific text to your donation receipt emails. Charitable does not support this out of the box, but thanks to the flexibility of the underlying code, it’s possible to enable this.

La solution

To solve this problem, we are going to add a new field to the Campaign editor in the WordPress dashboard. This field will allow you to add content.

In addition, we’ll add a new email tag that can be added to any donation email, including the Donation Receipt.

Best of all, we can achieve all of this with just two PHP functions! Let’s see how.

Step 1: Add our function

First of all, 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.
} );

Note that in this example we are creating what is known as an anonymous function; essentially, this is an unnamed function. This is fine as long as you are on a version of PHP greater than 5.2.

Not sure how to add code to your site? Here’s our rundown of three different ways you can add custom code to your site.

Step 2: Add the field to the Campaign editor

Since version 1.6, Charitable has included an API called the Campaign Fields API which provides an easy way to add new fields to the Campaign editor. This followed on from the Donation Fields API that we added in version 1.5.

Our next step is to use the Campaign Fields API to add our custom 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( 'campaign_email_content', array(
       'label' => 'Donation Email Content',
       'data_type' => 'meta',
       'admin_form' => array(
          'type' => 'textarea',
          'required' => false,
       ),
   ) );

    /**
     * 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 – campaign_email_content
– 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.

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 “Donation Email Content” field.

Step 3: Add a donation email tag

Now that we have our campaign field in place, the next step is to create a new email tag for donations. There are a few ways we could do this. One option is to use the Donation Fields API to register a new Donation field and automatically add an email tag for it. This would be appropriate if we want to use the field in multiple places, like the Donations export or within the donation meta.

In our case, we just want an email tag, so we are going to register just that. The first step is to create a new function that will be called on the charitable_email_donation_fields filter hook:

/**
 * We create a new function that will be called on the `charitable_email_donation_fields` filter.
 *
 * This function accepts two parameters:
 *
 * @param array $fields All registered donation email fields.
 * @param Charitable_Donation|null $donation When an email is being sent, this will be an instance of `Charitable_Donation`. Otherwise it's null.
 */
add_filter( 'charitable_email_donation_fields', function( $fields, $donation ) {
    Add our field here.
}, 10, 2 );

As with our function above, this is an anonymous function. But this one accepts a couple parameters. Since we want to use two parameters, we need to specify that in the final line of code, where we pass a priority of 10 and the number of parameters, 2.

Next, we will create a variable in our function called $field which will define the field.

/**
 * Define our field as an array.
 */
$field = array(
    'description' => 'Campaign-specific content',
    'preview' => 'This is some campaign-specific content.',
);

So far, this just sets a description and a preview-only value for the field. The preview value is what you see in place of the email shortcode when you click on the “Preview email” button in the email.

Our next step is to get the value to display when an email is sent:

/**
 * When this filter is called with a Donation object, we need to set
 * the `value` of the field to the campaign content. The rest of the
 * time, we don't need a `value` parameter.
 */
if ( ! is_null( $donation ) ) {
    /**
     * Get the campaign that received the donation.
     */
    $campaign_id = current( $donation->get_campaign_donations() )->campaign_id;
    $campaign = charitable_get_campaign( $campaign_id );

    /**
     * Set the `value` of our field to the campaign's email content.
     */
    $field['value'] = $campaign->get( 'campaign_email_content' );
}

In this code, we first check whether the $donation paramater is null. We have to check this because this filter (charitable_email_donation_fields) is not only called when a donation email is sent; it is also called at other times. For example, when you view the email settings page for the Donation Receipt email, this filter is called to get a full list of the donation email fields.

When we know that $donation is not null, we can get the campaign ID by using the $donation->get_campaign_donations() method, which gives us a set of rows that have all the campaign donations associated with a particular donation. Unless you are programatically creating donations or using our Easy Digital Downloads Connect integration, there will only be one row, so we get the first row by using current() and then get the campaign_id property from it.

$campaign_id = current( $donation->get_campaign_donations() )->campaign_id;

With $campaign_id in hand, we can call charitable_get_campaign( $campaign_id ) to get the Charitable_Campaign object.

$campaign = charitable_get_campaign( $campaign_id );

In turn, we set our field’s value property to the value of the campaign’s campaign_email_content field — the one we registered back in Step 2 above.

$field['value'] = $campaign->get( 'campaign_email_content' );

Finally, we add our field to the $fields array and return $fields, with our custom field included.

$fields['campaign_content'] = $field;

return $fields;

Step 4: Add the shortcode to the email content

If you have been following along, you should now have all the following code:

/**
 * We are creating a function which will be called on the `init` hook.
 */
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( 'campaign_email_content', array(
		'label'      => 'Donation Email Content',
		'data_type'  => 'meta',
		'admin_form' => array(
			'type'     => 'textarea',
			'required' => false,
		),
	) );

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

} );

/**
 * We create a new function that will be called on the `charitable_email_donation_fields` filter.
 *
 * This function accepts two parameters and must return an array.
 *
 * @param array                    $fields   All registered donation email fields.
 * @param Charitable_Donation|null $donation When an email is being sent, this will be an instance of `Charitable_Donation`. Otherwise it's null.
 */
add_filter( 'charitable_email_donation_fields', function( $fields, $donation ) {
	/**
	 * Define our field as an array.
	 */
	$field = array(
		'description' => 'Campaign-specific content',
		'preview'     => 'This is some campaign-specific content.',
	);

	/**
	 * When this filter is called with a Donation object, we need to set
	 * the `value` of the field to the campaign content. The rest of the
	 * time, we don't need a `value` parameter.
	 */
	if ( ! is_null( $donation ) ) {
		/**
		 * Get the campaign that received the donation.
		 */
		$campaign_id = current( $donation->get_campaign_donations() )->campaign_id;
		$campaign    = charitable_get_campaign( $campaign_id );

		/**
		 * Set the `value` of our field to the campaign's email content.
		 */
		$field['value'] = $campaign->get( 'campaign_email_content' );
	}

	/**
	 * Finally, we add our new field to the `$fields` array.
	 *
	 * The key used here (`campaign_content`) will become the email tag
	 * key, so the email tag would be shown like this:
	 *
	 * [charitable_email show=campaign_content]
	 */
	$fields['campaign_content'] = $field;

	return $fields;

}, 10, 2 );

There are just two functions included here, but together they do everything we need them to do.

The final step is to add the email shortcode to the email body, which can be done in the Email Settings area:

Once you have done this, test everything out by editing one of your campaigns, setting some campaign content and finally adding a test donation to the campaign. The email should contain your custom campaign-specific content.

Bonus tip: Add Easy Digital Downloads email tag

If you’re using our Easy Digital Downloads Connect extension and you would like to display your campaign-specific content in EDD’s purchase emails, you can drop in the code from this gist:

View the original gist on GitHub →

Enjoyed this?

I plan to write more tutorials like this to illustrate different ways in which you can customize and fine-tune Charitable to match your needs. This tutorial in particular was written in response to one user’s request, so if you have an idea for a topic you would love to see me cover in the future, send us an email via our Support page or leave a comment below.

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 Add Campaign-Specific Content to the Donation Receipt Email”

  1. This is great! Can html be used in this field to do something like bold a sentence?

    1. Avatar ericnicolaas
      ericnicolaas

      Good question Josh! HTML should work there.

      Cordialement,
      Eric

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 !

GiveWP Migrations Nouveau

Service de migration "White Glove" pour 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 !

Campagnes Nouveau

⏳ Compte à rebours de campagne : Créez de l'urgence et augmentez les dons

L'urgence est l'un des outils les plus puissants en collecte de fonds ! Découvrez le compte à rebours de campagne, un minuteur en direct et en temps réel conçu pour transformer la procrastination en générosité immédiate.

animation_compte_a_rebours_campagne

Quoi de neuf :

⏱️ Urgence en temps réel : Suivez magnifiquement les jours, heures, minutes et secondes jusqu'à la date limite de votre campagne avec des comptes à rebours visuels mis à jour en direct.

🎨 Adapté à votre style : Choisissez entre des tuiles bordées "Boxed" ou un affichage épuré "Inline" sur une seule ligne. Adaptez instantanément votre thème avec des contrôles de police et de couleur profonde.

🛠️ Placez-le n'importe où : Insérez le compte à rebours où vous le souhaitez en utilisant le champ "Campaign Builder", un bloc Gutenberg dédié, ou un simple shortcode.

🚨 Actions intelligentes à l'expiration : Contrôle total de l'état final : choisissez de remplacer automatiquement le minuteur par un message personnalisé, de le figer à zéro, et plus encore.