Skip to content

Instantly share code, notes, and snippets.

@ericnicolaas
Last active June 23, 2020 08:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericnicolaas/211d8b06c3c559d1809700257598af88 to your computer and use it in GitHub Desktop.
Save ericnicolaas/211d8b06c3c559d1809700257598af88 to your computer and use it in GitHub Desktop.
Adding a custom picture field to the campaign form
<?php
/**
* This function adds a custom text field to the campaign submission
* form, as well as the admin campaign editor, campaign emails, and
* campaign export.
*
* Note: This example requires Ambassadors 2+. For an example that worked
* on previous version, see the link below.
*
* @see https://github.com/Charitable/library/blob/master/extensions/ambassadors/legacy/add-text-field.php
*
* @return void
*/
add_action( 'init', function( $fields ) {
$fields = charitable()->campaign_fields();
// Create the field.
$field = new Charitable_Campaign_Field(
'custom_picture_field',
[
'label' => 'Custom Picture Field',
'data_type' => 'meta',
'campaign_form' => [
'required' => false,
'type' => 'picture',
'section' => 'campaign-details',
'priority' => 30,
],
'admin_form' => [
'type' => 'content',
'content' => '',
'base_path' => trailingslashit( __DIR__ ),
'view' => 'my-custom-picture-field-view',
'priority' => 1,
],
'show_in_export' => true,
'email_tag' => true,
]
);
// Register the field.
$fields->register_field( $field );
} );
@ericnicolaas
Copy link
Author

In order to display the picture in the admin, you need to configure the base_path and view arguments in the admin_form setting to correspond to a PHP file

For example, in the example above, the view file would be expected in the same directory where this function is defined, and would be called my-custom-picture-field-view.php.

In the view file, there is a $view_args variable available which is an array. It includes the ID of the uploaded photo with $view_args['value']. You can then display the photo using wp_get_attachment_image():

$photo_id = $view_args['value'];

wp_get_attachment_image( $photo_id );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment