Documentación de Charitable

Aprende a sacar el máximo partido a Charitable con instrucciones claras y paso a paso.

Charitable_Donation_Field

The Charitable_Donation_Field class allows you to create new donation fields or edit existing ones.

Tabla de Contenidos

Uso

Create a new donation field

If you want to add a new donation field, you will first need to create a new Charitable_Donation_Field instance, and then register it in the Donation Fields Registry.

add_action( 'init', function() {

    /* Create the Donation Field instance. */
    $field = new Charitable_Donation_Field(
        'my_custom_field',
        array(
            'label'          => __( 'My Custom Field' ),
            'data_type'      => 'meta', 
            'value_callback' => false,
            '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' ),
            ),
        )
    );

    /* Register it. */
    charitable()->donation_fields()->register_field( $field );
} );

Get an existing donation field

If you want to edit or change an existing donation field, the best way to do this is by getting the registered donation field object.

You can then use set() or the magic setter to update the field definition, or use the magic getter to get information about the field.

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

/* Get the Phone field. */
$field = $fields->get_field( 'phone' );

/* Change the label (magic setter). */
$field->label = 'Mobile No.';

/* Change the field to be required. */
$field->set( 'donation_form', 'required', true );

/* Print out the field's label (magic getter). */
echo $field->label;

Properties

field (string)

The field’s key, or identifier. Every field must have a unique key.

label (string)

The field’s label. This is a description of the field. This is what will be used in the donation form (unless you specifically override it in the donation_form argument), in the admin donation details area and in the donations export as the column header.

data_type (string)

The type of data that this field represents. There are two main options, with a third used mostly for internal Charitable purposes:

  • user: This is information that is specific to the donor, and will generally remain true for the donor in subsequent donations. Examples of this would include their name, phone number, etc.
  • meta: This is information that is specific to the donation. An example of this would be the payment gateway used for the donation, or whether the donor would like this donation to be made anonymously.
  • core: This is used primarily for internal purposes and should not be used in most cases. If you do use it, you will need to make sure you write additional code for storing the field value, as well as for getting it back from the database.

value_callback (false|callable)

How the field’s value will be retrieved. If you leave this out or set it to false, the default callback will be used based the field’s data type:

  • For a meta field, the default value callback is charitable_get_donor_meta_value.
  • For a user field, the default value callback is charitable_get_donation_meta_value.

You can specify your own value callback by passing your own function’s name, an array representing an object method [$class_name, $method_name], or an anonymous function.

donation_form (false|array)

How/whether the field will be included in the donation form. If this is left out or set to false, the field will not be included in the donation form at all. When passing an array, the following arguments are available:

  • label (string)
    The label shown in the donation form. If this is left out, the field’s label property will be used.
  • type (string)
    The type of field. Options include:
    • text
    • email
    • password
    • fecha
    • datepicker
    • checkbox
    • multi-checkbox
    • select
    • radio
    • file
    • fieldset
    • editor (uses the classic WordPress Editor)
    • textarea
    • number
    • picture
    • url
    • hidden
  • required (boolean)
    Whether this is a required field.
  • options (array)
    Provide a set of options. This is required when type is one of select, radio or multi-checkbox. These should be provided in a simple value => label array, where the label is what people see when they select an option, and value is what gets stored in the database.
  • default (mixed)
    The default value for this field.
  • placeholder (string)
    A placeholder shown in the field when it’s empty.
  • min (int)
    Set the minimum allowed number. Only applicable if type is number.
  • max (int)
    Set the maximum allowed number. Only applicable if type is number.
  • attrs (array)
    An array of arbitrary attributes to be added to the input field.
  • section (string)
    The section of the donation form this should appear in. There are two sections by default: user and meta. If this is not set, the section will be based on the field’s data type.
  • show_before (string)
    Sets where the field should be added in the donation form by specifying the field it should appear before.
  • show_after (string)
    Sets where the field should be added in the donation form by specifying the field it should appear after.
  • priority (int)
    Set the position of the field within the form. This is used unless show_after or show_before are set for the field. If priority, show_after and show_before are not set, the field will be shown after the most recently registered form field.
  • value_callback (false|callable)
    A callback function to retrieve the value of the field for a donation. This will override the value_callback setting for the field.

admin_form (boolean|array)

Sets whether the field should be shown in the admin donation form.

  • If this is set to false, the field will not be shown in the admin donation form (not even as a hidden input).
  • If this is set to true, the form field will inherit arguments from the donation_form (if provided), or use default arguments.
  • Alternatively, you can pass an array of values to fine-tune how this field is shown in the admin form (all the same arguments are accepted as for donation_form above).

show_in_meta (boolean)

Whether to include this in the “Donation Details” section of a single donation details admin page.

show_in_export (boolean)

Whether to include this in the Donations export available from Charitable > Donations.

email_tag (boolean|array)

Whether to create an email tag for this field.

  • If this is false, no email tag will be created.
  • If this is true, an email tag will be created, using the field label as the description. No preview value will be set.
  • Alternatively, pass an array for finer control over the email tag details:
    • description (string)
      The description shown for the email tag. If no description is set, the field’s label will be used.
    • tag (string)
      The email tag. If this is not provided, the field key will be used.
    • preview (mixed)
      A value to use in email previews for this field.

Methods

require()

Added in version 1.5.0

Create a new Donation Field instance.

Arguments

  • $field (string)

    The field’s unique key.

  • $args (array)

    An array containing any of the properties shown above, except for $field.

Uso

$field = new Charitable_Donation_Field(
    'my_custom_field',
    array(
        'label'          => __( 'My Custom Field' ),
        'data_type'      => 'meta', 
        'value_callback' => false,
        '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' ),
        ),
    )
);

require()

Added in version 1.6.0

Change a field argument.

Arguments

  • key (string)

    The field argument to change. This can be any of the properties outlined above, except for $field: label, data_type, value_callback, donation_form, admin_form, show_in_meta, show_in_export, email_tag.

  • setting (string)

    This identifies a specific array element within one of the array-compatible arguments: donation_formadmin_formemail_tag. Note: If $key is not one of those three, leave this as an empty string.

  • $value (mixed)

    The new value for this field argument.

Uso

/* Get the State field. */
$field = charitable()->donation_fields()->get_field( 'state' );

/* Change the label to Province. */
$field->set( 'label', '', 'Province' );

/* Change the field to be required. */
$field->set( 'donation_form', 'required', true );

require()

Added in version 1.5.0

Change the field’s parameters. Unlike the set() method described above, this does not allow you to update a single element within an array-like argument (you can’t use it to easily change whether a field is required in the donation form, for example).

It’s the equivalent of calling set() with the $setting argument left as an empty string.

Note: __set() is a magic method in PHP. It is called implicitly when you try to set one of the class properties, other than $field.

Arguments

  • $key (string)

    The field argument to change. This can be any of the properties outlined above, except for $fieldlabeldata_typevalue_callbackdonation_formadmin_formshow_in_metashow_in_exportemail_tag.

  • $value (mixed)

    The new value for this field argument.

Uso

/* Get the State field. */
$field = charitable()->donation_fields()->get_field( 'state' );

/* Change the label to Province. */
$field->label = 'Province';

require()

Added in version 1.5.0

Get the field’s value for a particular argument.

Note: __get() is a magic method in PHP. It is called implicitly when you try to access a class property.

Arguments

  • $key (string)

    The field argument to retrieve.

Uso

/* Get the State field. */
$field = charitable()->donation_fields()->get_field( 'state' );

/* Print/echo the current label. */
echo $field->label;

¿Todavía tienes preguntas? ¡Estamos aquí para ayudarte!

Última modificación:

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.