Home / Archive / Add Donate Button
Duplicate Snippet

Embed Snippet on Your Site

Add Donate Button

Code Preview
php
<?php
/**
 * USAGE:
 *
 * To display a particular campaign's button, just add this to your template:
ed_charitable_get_campaign_donate_button( 123 );
 * Replace 123 with the ID of your campaign.
 */
/**
 * Display a donate button for a specific campaign.
 *
 * Clicking on "Donate" will open the donation form modal directly
 * on the page.
 *
 * @param  int $campaign_id
 * @return string
 */
function ed_charitable_get_campaign_donate_button( $campaign_id ) {
	// Get the campaign.
	$campaign = charitable_get_campaign( $campaign_id );
	// Add the donate modal window to the footer. This is invisible until the button is clicked.
	add_action(
		'wp_footer',
		function() use ( $campaign ) {
			charitable_template( 'campaign/donate-modal-window.php', array( 'campaign' => $campaign ) );
		}
	);
	ob_start();
	// Render the donate button.
	charitable_template_donate_button( $campaign );
	// Load scripts that are required for the modal to work.
	Charitable_Public::get_instance()->enqueue_donation_form_scripts();
	return ob_get_clean();
}
/**
 * To add a shortcode to display a campaign's donate button, include this function below.
 *
 * @param  array $atts User-defined shortcode attributes.
 * @return string
 */
function ed_charitable_campaign_donate_button_shortcode( $atts ) {
	if ( ! array_key_exists( 'campaign_id', $atts ) ) {
		return '';
	}
	return ed_charitable_get_campaign_donate_button( $atts['campaign_id'] );
}
add_shortcode( 'charitable_donate_button', 'ed_charitable_campaign_donate_button_shortcode' );

Comments

Add a Comment

  1. Hi there, I’ve tried adding this to my website but can’t quite get it to work.
    What do I need to change in the code to reference the specific campaign? Do I add a seperate snippet of code for each campaign I want to add?
    Code snippet automatically creates a shortcode (something like [wpcode id="8330"]) so I assume I just add this as a short code?

  2. Jordan,

    The above snippet should be added “everywhere” in WPCode and then you can add the function to a page on your site (as noted in the top comments) in PHP:

    ed_charitable_get_campaign_donate_button( 123 );

    ‘123’ would be the campaign ID. For this we reocmmend one button/modal per page. For a regular button in PHP that points to a campaign page, that’s more straightforward:

    echo get_permalink( 123);

    This is a WordPress function that should result in http://www.testsite.com/campaign – if you always have /donate you can simply add that (in this example of a potential button:r

    <a href="”>Donate

    There are no shortcodes involved here in terms of what to add. There ARE shortcodes to add a donation form, for example:r

    https://www.wpcharitable.com/documentation/add-your-donation-form-to-a-page

    I hope this helps.