Documentation Charitable

Apprenez à tirer le meilleur parti de Charitable grâce à des instructions claires, étape par étape.

API des champs de don

The Donation Fields API is provides a powerful, flexible way to add, remove and edit your donation fields.

What are donation fields?

Donation fields are any bits of information about a donation that are available for you to use. As an example, here are some of the fields available by default:

  • first_name – Get the first name of the donor.
  • last_name – Get the last name of the donor.
  • amount_formatted – Get the donation amount, formatted according to your site’s currency settings (e.g. $50.00).
  • date – The date that the donation was made.
  • gateway_label – The payment method the donor used.

How do I get the value for a particular donation field?

You can get the value of any donation field through the donation’s Charitable_Donation object.

The first step is to get a Charitable_Donation object:

$donation_id = 123; // Replace with your Donation's ID.
$donation    = charitable_get_donation( $donation_id );

Next, you can get the field’s value by calling get() on the object, as you can see in the examples below:

$first_name = $donation->get( 'first_name' );
$date       = $donation->get( 'date' );
$gateway    = $donation->get( 'gateway_label' );

To put it all together:

$donation_id = 123;
$donation    = charitable_get_donation( $donation_id );
$first_name  = $donation->get( 'first_name' );

How do I add a new field to my donation form?

Adding a new field is a two-step process.

First, you will create a new Charitable_Donation_Field object which will define your field’s parameters: its label, the type of value it stored, how it should be included in the donation form (if at all), whether it should be added to the Donations export file, and more.

Next, you add this field to the Charitable_Donation_Field_Registry class, which provides a way to store and retrieve donation fields.

Let’s see how this works in an example:

/**
 * Create a callback function on the `init` hook, where we
 * can register our donation field.
 */
add_action( 'init', function() {

    /* Create the `Charitable_Donation_Field` object. */
    $field = new Charitable_Donation_Field(
        'my_custom_field',
        array(
            'label'          => __( 'My Custom Field' ),
            'data_type'      => 'meta', 
            'donation_form'  => array(
                'type'       => 'text',
                'required'   => false,
                'show_after' => 'phone',
            ), 
            'admin_form'     => true,
            'show_in_meta'   => true,
            'show_in_export' => true,
            'email_tag'      => array(
                'description' => __( 'The custom field value' ),
            ),
        )
    );

    /* Get the `Charitable_Donation_Field_Registry` instance. */
    $fields = charitable()->donation_fields();

    /* Add the new field. */
    $fields->register_field( $field );
} );

In the example above, we have created a new field with a key of my_custom_field. Here’s what its defined parameters mean:

  • Its label is “My Custom Field”. This is what will be used in the donation form, in the admin donation details area and in the donations export as the column header.
  • Its data type is meta. This means that it will be stored as a meta field specific to that donation.
  • It is set up to be shown in the donation form, right after the phone field. It’s an optional field.
  • It will also be added to the admin donation form.
  • When viewing the details for the donation, you will be able to see what the donor entered for this field in the “Donation Details” section.
  • When you download a donations export, a new “My Custom Field” column will be added, showing what donors entered for this field.
  • A new email tag has been created for this field, so you can easily include it in donation-specific emails, like the Donation Receipt (for donors), or the Donation Notification (for administrators).

This is a relatively simple example, but it achieves a lot. Click here for a more detailed breakdown of all the available parameters when creating Charitable_Donation_Field objects.

How do I change an existing donation field?

To change an existing donation field, you first retrieve the field from the Charitable_Donation_Field_Registry, and then update the field value.

To update the field value, we can call set() on the field, or use the magic setter.

/**
 * Create a callback function on the `init` hook, where we
 * can start changing the donation field.
 */
add_action( 'init', function() {

    /* Get the Donation Field Registry object. */
    $fields = charitable()->donation_fields();

    /* Get the field we want to change. */
    $field  = $fields->get_field( 'phone' );
    
    /**
     * Change #1: Make it a required field (uses set()).
     * Change #2: Change the label (uses magic setter).
     */
    $field->set( 'donation_form', 'required', true );
    $field->label = 'Phone Number';
} );

For more information about how to update field arguments, see the detailed reference for those class methods:

How do I add a field to a specific campaign’s donation form?

If you want a new or existing field to only show for certain campaigns, you can do this by adding a new function which controls whether the field shows in the donation form.

If you are adding a new field, you will first to create the donation field, so follow those steps first.

Now you can hide the field you registered from all donation forms other than the one you want it to show on:

add_filter( 'charitable_donation_form_user_fields', function( $fields, $form ) {

    /* If the field doesn't exist, stop right here. */
    if ( ! array_key_exists( 'my_custom_field', $fields ) ) {
        return $fields;
    }

    /* Match any campaign that DOESN'T have a slug of 'special-campaign' */
    if ( 'special-campaign' !== $form->get_campaign()->post_name ) {    
        unset( $fields['my_custom_field'] );
    }
    
    return $fields;
}, 10, 2 );

What’s happening here?

  • We only want the my_custom_field field to show on the campaign with a slug of ‘special-campaign’.
  • The field will show in all campaigns by default, so our code checks if the campaign doesn’t have a slug of ‘special-campaign’ and then removes it.

You can change the condition under which the field is shown. For example, you can change the field to only show for campaigns in a certain category, or for campaigns that have a specific parent campaign (i.e. fundraisers for one of your peer-to-peer fundraising campaigns).

How do I change a donation field for a particular campaign?

The approach used above to show a field on a particular campaign can be adapted to change a donation field for a particular campaign.

For example, if you only want to accept donations from donors in a specific country for a certain campaign, you can achieve that with the following code:

add_filter( 'charitable_donation_form_user_fields', function( $fields, $form ) {
    /* If a country field doesn't exist, stop right here. */
    if ( ! array_key_exists( 'country', $fields ) ) {
        return $fields;
    }

    if ( 'south-africa-only' === $form->get_campaign()->post_name ) {
        $fields['country']['options'] = array(
            'ZA' => 'South Africa',
        );
    }	

    return $fields;

}, 10, 2 );

This code will make it so that the campaign with a slug of ‘south-africa-only’ will only display South Africa as a valid country option.

How do I make a donation field show based on user input?

The previous two examples showed how to add / change donation fields based on the donation form’s campaign. But what if you want to show or hide a field based on user input?

Handling this requires a different approach, using Javascript. If you are a confident developer, you can add this through a new Javascript file, but in the example below we will use the wp_add_inline_script function to add our custom Javascript without needing to create, register and enqueue a new script.

In the example below, we are only showing our custom field, my_custom_field, when the donor is from the United States:

add_action( 'wp_enqueue_scripts', function() {
    wp_add_inline_script( 'charitable-script', "
        jQuery('body').on('charitable:form:loaded', (event, donationForm) => {
            var countryField = donationForm.get_input('country');
            function toggleCustomField() {
                donationForm.get_input('my_custom_field').parent().toggle('US' === countryField.val());
            }
            countryField.on('change', toggleCustomField).trigger('change');
        });
    " );
} );

Full list of default donation fields

The following fields are added by Charitable and its extensions:

CléDescription
donation_idThe donation ID
first_nameThe donor’s first name.
last_nameThe donor’s last name.
donorThe donor’s full name.
emailThe donor’s email address.
donor_addressThe donor’s full address, formatted.
addressThe donor’s first address field.
address_2The donor’s second address field.
cityThe donor’s city.
stateThe donor’s state.
postcodeThe donor’s postcode.
countryThe donor’s country.
phoneThe donor’s phone number.
campaignsThe campaign that received the donation.
campaign_categories_listThe categories that the campaign is in.
amount_formattedThe donation amount, formatted according to your currency settings.
dateThe date of the donation.
timeThe time the donation was made.
statusThe donation status. This returns the raw value of post_status.
status_labelThe donation status as a more readable label.
donation_gatewayThe payment gateway used for the donation.
gateway_labelThe payment gateway as a reader-friendly string.
donation_keyThe unique donation key.
gateway_transaction_idThe transaction ID for the donation in the payment gateway that was used (i.e. PayPal, Stripe).
test_modeWhether the donation was made in test mode.
donation_summaryA readable summary of the donation, listing the campaign receiving the donation & the amount donated.
contact_consentWhether the donor gave their consent to be contacted.
cover_feesWhether the donor covered fees.
Added by Fee Relief.
fee_amountThe amount of processing fees paid by the donor.
Added by Fee Relief.
fee_amount_formattedThe amount of processing fees paid by the donor, formatted according to your currency settings.
Added by Fee Relief.
total_donation_with_feesThe total donation amount including processing fees.
Added by Fee Relief.
total_donation_with_fees_formattedThe total donation amount including processing fees, formatted according to your currency settings.
Added by Fee Relief.
consent_to_trackWhether the donor has given permission to have their newsletter activity tracked (opens, clicks). This only applies if you are using Campaign Monitor.
Added by Newsletter Connect.
anonymous_donationWhether the donor chose to remain anonymous.
Added by Anonymous Donations.
donor_commentThe comment left by the donor.
Added by Donor Comments.
giftaidWhether the donor claimed Gift Aid.
Added by Gift Aid.
giftaid_declarationThe declaration the donor agreed to when they claimed Gift Aid.
Added by Gift Aid.
titleThe donor’s title (Mr, Mrs, Ms, etc.).
Added by Gift Aid.
address_3The third line in the donor’s address.
Added by Gift Aid.

Vous avez encore des questions ? Nous sommes là pour vous aider !

Dernière modification :

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.