How to Add Donation Buttons on Checkout Page

How to Add Donation Buttons on Checkout Page

Adding donation buttons on the checkout page of an e-commerce website can be a great way to encourage customers to contribute to a cause or support a charitable organization. In this article, we will discuss how to add donation buttons on the checkout page using the provided code snippet.

The code snippet provided is a part of a class called “LavBoostModuleDonation” which extends another class called “LavBoostModule.” This class is responsible for adding the necessary functionality to enable and display donation buttons on the checkout page. Let’s break down the code and understand its different components.

  • run( $args = ” ): This method is the entry point of the class. It creates the settings tab and adds various actions and hooks related to the donation functionality. It checks if the donation feature is enabled and then adds the necessary actions for AJAX and rendering.
 public function run( $args = '' ) {
    $this->createSettingsTab();

    if ( $this->getValue( 'donation_enable' ) ) {
        add_action( 'wp_enqueue_scripts', array( $this, 'localize' ), 99 );
        add_action( 'woocommerce_review_order_before_submit', array( $this, 'render' ), 9999 );

        // AJAX action to add a product to cart
        add_action( 'wp_ajax_add_to_cart', array( $this, 'addToCartAjax' ) );
        add_action( 'wp_ajax_nopriv_add_to_cart', array( $this, 'addToCartAjax' ) );

        // AJAX action to remove a product from cart
        add_action( 'wp_ajax_remove_cart_item', array( $this, 'removeCartItemAjax' ) );
        add_action( 'wp_ajax_nopriv_remove_cart_item', array( $this, 'removeCartItemAjax' ) );
    }
}
  • localize(): This method is responsible for localizing JavaScript variables used for AJAX functionality. It uses the wp_localize_script() function to pass the ajaxurl and nonce variables to the client-side script.
public function localize() {
    wp_localize_script( 'lav-boost', 'lavBoostDonate', array(
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
        'nonce'   => wp_create_nonce( 'nonce-lav-boost-donate' )
    ) );
} 
  • addToCartAjax(): This method handles the AJAX request for adding a donation product to the cart. It checks for the presence of the required nonce and product ID, verifies the nonce, adds the product to the cart using WC()->cart->add_to_cart(), calculates the cart totals, and sends a JSON response back to the client.
public function addToCartAjax() {
    if ( isset( $_POST['product_id'] ) ) {
        if ( empty( $_POST['nonce'] ) || empty( $_POST['product_id'] ) ) {
            wp_die( '0' );
        }

        if ( check_ajax_referer( 'nonce-lav-boost-donate', 'nonce', false ) ) {
            // Process adding the product to the cart
            // ...

            wp_send_json( [
                'title' => esc_html__( 'Donate has been added to your cart', 'lav-boost' ),
                'data'  => $cart_item_data,
                'key'   => $keyItem
            ] );
            wp_die();
        } else {
            wp_die( esc_html__( 'Access denied', 'lav-boost' ), esc_html__( 'Denied', 'lav-boost' ), 403 );
        }
    }

    wp_die( '0' );
}

removeCartItemAjax(): This method handles the AJAX request for removing a donation product from the cart. It checks for the presence of the required nonce and product ID, verifies the nonce, removes the product from the cart using WC()->cart->remove_cart_item(), and sends a JSON response indicating the success of the removal.

public function removeCartItemAjax() {
    if ( isset( $_POST['product_key'] ) ) {
        if ( empty( $_POST['nonce'] ) || empty( $_POST['product_key'] ) ) {
            wp_die( '0' );
        }

        if ( check_ajax_referer( 'nonce-lav-boost-donate', 'nonce', false ) ) {
            // Process removing the product from the cart
            // ...

            wp_send_json( [
                'result' => 'success',
                'msg'    => esc_html__( 'Product removed from cart', 'lav-boost' ),
                'key'    => $_POST['product_key']
            ] );
            wp_die();
        } else {
            wp_die( esc_html__( 'Access denied', 'lav-boost' ), esc_html__( 'Denied', 'lav-boost' ), 403 );
        }
    }

    wp_die( '0' );
}
  • render(): This method generates the HTML output for the donation buttons on the checkout page. It retrieves the donation product IDs and their associated details from the class settings. It then generates the necessary HTML markup for each donation button, including a checkbox input and label.
<?php
public function render() {
    $donation_products = $this->getValue( 'donation_products', array() );

    if ( ! empty( $donation_products ) ) {
        foreach ( $donation_products as $product_id ) {
            $product = wc_get_product( $product_id );

            if ( $product ) {
                echo '<div class="donation-checkbox">';
                echo '<input type="checkbox" name="lav_boost_donation_product[]" value="' . esc_attr( $product_id ) . '">';
                echo '<label>' . esc_html( $product->get_name() ) . '</label>';
                echo '</div>';
            }
        }
    }
}
?>

Conclusion

The provided code snippet demonstrates a practical approach to generate HTML checkboxes dynamically based on donation product values. By retrieving the product information and properly constructing the HTML elements, we ensure that the checkboxes and labels are accurately rendered. This implementation can be useful in scenarios where users can select multiple donation products.

It’s important to note that the code assumes the availability of the wc_get_product() function and incorporates measures to escape and sanitize data, which helps enhance security and prevent vulnerabilities.

Remember to adapt the code to your specific requirements and thoroughly test it within your development environment. By leveraging this code snippet, you can enhance the functionality and user experience of your WordPress website, especially in scenarios involving donation-related features.