Blog benéfico

Todo lo que necesitas saber sobre Charitable y nuestro equipo.

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

Última actualización el

  • Por

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.

The 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.

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

      Good question Josh! HTML should work there.

      Saludos,
      Eric

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!

GiveWP Migraciones Nuevo

Servicio de Migración "White Glove" para 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.

Campañas Nuevo

⏳ Cuenta atrás de la campaña: genere urgencia y aumente las donaciones

¡La urgencia es una de las herramientas más poderosas en la recaudación de fondos! Conozca Campaign Countdown, un temporizador en vivo y en tiempo real diseñado para convertir la procrastinación en generosidad inmediata.

animación de cuenta atrás de campaña

Novedades:

⏱️ Urgencia en vivo y en tiempo real: rastree bellamente días, horas, minutos y segundos hasta la fecha límite de su campaña con cuentas atrás visuales que se actualizan en vivo.

🎨 Adaptado a su estilo: elija entre mosaicos con borde "Boxed" o una pantalla "Inline" limpia y de una sola línea. Adapte su tema al instante con controles de fuente y color profundo.

🛠️ Colóquelo en cualquier lugar: inserte la cuenta atrás donde desee utilizando el campo Campaign Builder, un bloque Gutenberg dedicado o un simple shortcode.

🚨 Acciones inteligentes de caducidad: control total sobre el estado final: elija reemplazar automáticamente el temporizador con un mensaje personalizado, congelarlo en cero y más.