Replacing WooCommerce Plugins With AI-Generated Code Snippets

Free code snippets generated by CodeWP's AI, made to add core functions of paid WooCommerce plugins like shipment tracking, custom checkout pages, and conditional payments.
calendar_today
Published: March 3, 2023
Founder & CEO
AI Tools For WordPress Creators
Code, learn, troubleshoot, and secure WordPress sites with the CodeWP platform and our custom AI.
Start for Free
Contents

In this article, we'll offer you over $300 of value by providing code snippets that fulfill the same tasks as popular WooCommerce extensions. All of these WooCommerce code snippets were generated on the CodeWP platform using AI.

These snippets will do the same core functionality as these premium plugins, but won't be as full-featured, with multiple settings, admin options pages, etc (though you could likely do this with the right collection of related prompts, based of the ones below).

Therefore, it's not the most fair comparison - $300+ in value - but there's still an argument to be made 😉.

Code Snippet For WooCommerce Shipment Tracking

WooCommerce Shipment Tracking is a plugin designed for online store owners who want to provide their customers with a way to track their shipment status. This plugin integrates with various shipping carriers, including USPS, UPS, FedEx, DHL, and more, allowing customers to track their orders directly on the store's website.

This plugin costs $49.00/yr.

This snippet adds the core functionality of the plugin for free:

  • Manually (or automatically, using the api below) add the tracking number and carrier
  • Add the hyperlinked tracking number to all emails
  • Add the hyperlinked tracking number to the order confirmation
PHP
class CWPAI_Shipping_Tracking {
    public function __construct() {
        add_action( 'add_meta_boxes', array( $this, 'add_metabox' ) );
        add_action( 'admin_footer', array( $this, 'add_js' ) );
        add_action( 'woocommerce_email_after_order_table', array( $this, 'add_tracking_info_to_email' ) );
        add_action( 'woocommerce_view_order', array( $this, 'add_tracking_info_to_order_page' ) );
    }

    public function add_metabox() {
        add_meta_box(
            'cwpai_shipping_tracking',
            __( 'Shipping Tracking', 'cwpai' ),
            array( $this, 'metabox_content' ),
            'shop_order',
            'side',
            'default'
        );
    }

    public function metabox_content() {
        global $post;
        $tracking_number = get_post_meta( $post->ID, '_cwpai_tracking_number', true );
        $carrier_name = get_post_meta( $post->ID, '_cwpai_carrier_name', true );
        ?>
        <p>
            <label for="cwpai_tracking_number"><?php _e( 'Tracking Number', 'cwpai' ); ?></label>
            <input type="text" name="cwpai_tracking_number" id="cwpai_tracking_number" value="<?php echo esc_attr( $tracking_number ); ?>" />
        </p>
        <p>
            <label for="cwpai_carrier_name"><?php _e( 'Carrier Name', 'cwpai' ); ?></label>
            <select name="cwpai_carrier_name" id="cwpai_carrier_name">
                <option value=""><?php _e( 'Select a carrier', 'cwpai' ); ?></option>
                <option value="fedex" <?php selected( $carrier_name, 'fedex' ); ?>><?php _e( 'FedEx', 'cwpai' ); ?></option>
                <option value="ups" <?php selected( $carrier_name, 'ups' ); ?>><?php _e( 'UPS', 'cwpai' ); ?></option>
                <option value="usps" <?php selected( $carrier_name, 'usps' ); ?>><?php _e( 'USPS', 'cwpai' ); ?></option>
                <option value="custom" <?php selected( $carrier_name, 'custom' ); ?>><?php _e( 'Custom', 'cwpai' ); ?></option>
            </select>
        </p>
        <?php
    }

    public function add_js() {
        global $post_type;
        if ( 'shop_order' !== $post_type ) {
            return;
        }
        ?>
        <script type="text/javascript">
            jQuery( function( $ ) {
                $( '#cwpai_carrier_name' ).select2();
            } );
        </script>
        <?php
    }

    public function add_tracking_info_to_email( $order ) {
        $tracking_number = get_post_meta( $order->get_id(), '_cwpai_tracking_number', true );
        $carrier_name = get_post_meta( $order->get_id(), '_cwpai_carrier_name', true );
        if ( ! $tracking_number || ! $carrier_name ) {
            return;
        }
        ?>
        <h2><?php _e( 'Tracking Information', 'cwpai' ); ?></h2>
        <p>
            <strong><?php _e( 'Tracking Number:', 'cwpai' ); ?></strong>
            <?php echo esc_html( $tracking_number ); ?>
        </p>
        <p>
            <strong><?php _e( 'Carrier:', 'cwpai' ); ?></strong>
            <?php echo esc_html( $carrier_name ); ?>
        </p>
        <?php
        if ( in_array( $carrier_name, array( 'fedex', 'ups', 'usps' ) ) ) {
            echo $this->get_tracking_url( $carrier_name, $tracking_number );
        }
    }

    public function add_tracking_info_to_order_page( $order_id ) {
        $tracking_number = get_post_meta( $order_id, '_cwpai_tracking_number', true );
        $carrier_name = get_post_meta( $order_id, '_cwpai_carrier_name', true );
        if ( ! $tracking_number || ! $carrier_name ) {
            return;
        }
        ?>
        <h2><?php _e( 'Tracking Information', 'cwpai' ); ?></h2>
        <p>
            <strong><?php _e( 'Tracking Number:', 'cwpai' ); ?></strong>
            <?php echo esc_html( $tracking_number ); ?>
        </p>
        <p>
            <strong><?php _e( 'Carrier:', 'cwpai' ); ?></strong>
            <?php echo esc_html( $carrier_name ); ?>
        </p>
        <?php
        if ( in_array( $carrier_name, array( 'fedex', 'ups', 'usps' ) ) ) {
            echo $this->get_tracking_url( $carrier_name, $tracking_number );
        }
    }

    private function get_tracking_url( $carrier_name, $tracking_number ) {
        switch ( $carrier_name ) {
            case 'fedex':
                $url = 'https://www.fedex.com/apps/fedextrack/?tracknumbers=' . $tracking_number;
                break;
            case 'ups':
                $url = 'https://www.ups.com/track?loc=en_US&tracknum=' . $tracking_number;
                break;
            case 'usps':
                $url = 'https://tools.usps.com/go/TrackConfirmAction?tLabels=' . $tracking_number;
                break;
            default:
                return '';
        }
        return '<p><a href="' . esc_url( $url ) . '" target="_blank">' . __( 'Click here to track your shipment', 'cwpai' ) . '</a></p>';
    }
}

new CWPAI_Shipping_Tracking();

What about API access?

A lot of fulfillment platforms let you stick tracking numbers onto orders without lifting a finger. But what if we want to go one step further and make a new thingy that gives people and platforms API access, so they can just automatically add tracking info to our orders?

Easy:

PHP
add_action( 'rest_api_init', 'cwpai_register_tracking_endpoint' );
function cwpai_register_tracking_endpoint() {
    register_rest_route( 'cwpai/v1', '/tracking/', array(
        'methods'  => 'POST',
        'callback' => 'cwpai_tracking_endpoint_callback',
        'args'     => array(
            'order_id'        => array(
                'required'          => true,
                'validate_callback' => 'cwpai_validate_order_id',
            ),
            'tracking_number' => array(
                'required'          => true,
                'validate_callback' => 'cwpai_validate_tracking_number',
            ),
            'carrier_name'    => array(
                'required'          => true,
                'validate_callback' => 'cwpai_validate_carrier_name',
            ),
            'order_status'    => array(
                'required'          => true,
                'validate_callback' => 'cwpai_validate_order_status',
            ),
        ),
        'permission_callback' => 'cwpai_permission_callback',
    ) );
}

function cwpai_tracking_endpoint_callback( $request ) {
    $order_id        = $request['order_id'];
    $tracking_number = $request['tracking_number'];
    $carrier_name    = $request['carrier_name'];
    $order_status    = $request['order_status'];

    $order = wc_get_order( $order_id );
    if ( ! $order ) {
        return new WP_Error( 'cwpai_invalid_order_id', 'Invalid order ID.', array( 'status' => 400 ) );
    }

    update_post_meta( $order_id, '_cwpai_tracking_number', $tracking_number );
    update_post_meta( $order_id, '_cwpai_carrier_name', $carrier_name );
    $order->update_status( $order_status );

    return array(
        'order_id'        => $order_id,
        'tracking_number' => $tracking_number,
        'carrier_name'    => $carrier_name,
        'order_status'    => $order_status,
    );
}

function cwpai_validate_order_id( $order_id ) {
    return is_numeric( $order_id );
}

function cwpai_validate_tracking_number( $tracking_number ) {
    return is_string( $tracking_number );
}

function cwpai_validate_carrier_name( $carrier_name ) {
    return is_string( $carrier_name );
}

function cwpai_validate_order_status( $order_status ) {
    return array_key_exists( $order_status, wc_get_order_statuses() );
}

function cwpai_permission_callback() {
    return current_user_can( 'manage_woocommerce' ) || current_user_can( 'manage_options' );
}

Add New Tab to "My Account" page

This code adds an affiliate tab to the WooCommerce "My Account" menu and creates an endpoint for it. When a user clicks on the "Affiliate" tab, they will be redirected to the specified URL.

This is a subfeature of the plugin Customize My Account for WooCommerce, which comes in at $49.00/yr.

PHP
add_filter ( 'woocommerce_account_menu_items', 'cwpai_add_affiliate_tab', 40 );
function cwpai_add_affiliate_tab( $menu_links ){
    $menu_links = array_slice( $menu_links, 0, 5, true )
    + array( 'affiliate' => 'Affiliate' )
    + array_slice( $menu_links, 5, NULL, true );
    return $menu_links;
}

add_action( 'init', 'cwpai_add_endpoint' );
function cwpai_add_endpoint() {
    add_rewrite_endpoint( 'affiliate', EP_ROOT | EP_PAGES );
}

add_action( 'woocommerce_account_affiliate_endpoint', 'cwpai_affiliate_endpoint_content' );
function cwpai_affiliate_endpoint_content() {
    wp_redirect( 'https://example.com' );
    exit;
}

WooCommerce Slack Notifications

This code is a WooCommerce action that sends a notification message to a Slack channel when a new order is completed.

It fulfills the core feature that WooCommerce Slack, which costs $29.00/yr is built to address.

The action is triggered when an order status is changed to "completed" and it calls the function cwpai_woo_send_slack_message.

Inside the function, the order details are retrieved using the $order_id parameter and various order data is extracted, such as the total amount, customer email, customer name, and order type (either a single product or a subscription). The product name is retrieved from the order items and the product type is determined based on whether it's a subscription or not.

A message is then constructed using the extracted data, and a Slack webhook URL is provided to send the message to the designated channel. The message is sent using the curl function and the json_encode function is used to convert the message data to JSON format.

PHP
add_action( 'woocommerce_order_status_completed', 'cwpai_woo_send_slack_message' );
function cwpai_woo_send_slack_message( $order_id ) {
    $order = wc_get_order( $order_id );
    $order_data = $order->get_data();
    $order_items = $order->get_items();
    $order_total = $order->get_total();
    $order_email = $order_data['billing']['email'];
    $order_name = $order_data['billing']['first_name'] . ' ' . $order_data['billing']['last_name'];
    $order_type = '';
    foreach ( $order_items as $item ) {
        $product_id = $item->get_product_id();
        $product = wc_get_product( $product_id );
        $product_name = $product->get_name();
        $product_type = $product->get_type();
        if ( $product_type == 'subscription' ) {
            $order_type = 'Subscription';
        } else {
            $order_type = 'Single';
        }
    }
    $slack_message = 'New ' . $order_type . ' Order: ' . $order_total . ' - ' . $product_name . ' - ' . $order_name . ' - ' . $order_email;
    $slack_webhook_url = 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX';
    $slack_data = array(
        'text' => $slack_message
    );
    $slack_data_string = json_encode( $slack_data );
    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_URL, $slack_webhook_url );
    curl_setopt( $ch, CURLOPT_POST, 1 );
    curl_setopt( $ch, CURLOPT_POSTFIELDS, $slack_data_string );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
    curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'Content-Length: ' . strlen( $slack_data_string )
    ) );
    $result = curl_exec( $ch );
    curl_close( $ch );
}

Custom WooCommerce Thank You Page Redirect

This code adds a custom field to WooCommerce products that allows the user to specify a redirect URL for the customer after they purchase the product.

It's comparable to Custom Thank You Pages, which costs $49.00/yr.

The first function adds the custom field to the product options in the WooCommerce admin panel. The second function saves the custom field data when the product is saved. The third function hooks into the WooCommerce thankyou page and retrieves the order information. It then checks if the product has a redirect URL specified and redirects the customer to that URL after the purchase is complete.

PHP
add_action( 'woocommerce_product_options_general_product_data', 'cwpai_woo_add_custom_general_fields' );
function cwpai_woo_add_custom_general_fields() {
    global $woocommerce, $post;
    echo '<div class="options_group">';
    woocommerce_wp_text_input(
        array(
            'id' => '_cwpai_woo_redirect_url',
            'label' => __( 'Redirect URL', 'woocommerce' ),
            'placeholder' => 'http://',
            'desc_tip' => 'true',
            'description' => __( 'Enter the URL the customer will be redirected to after purchasing this product.', 'woocommerce' )
        )
    );
    echo '</div>';
}
add_action( 'woocommerce_process_product_meta', 'cwpai_woo_add_custom_general_fields_save' );
function cwpai_woo_add_custom_general_fields_save( $post_id ){
    $woocommerce_text_field = $_POST['_cwpai_woo_redirect_url'];
    if( !empty( $woocommerce_text_field ) )
        update_post_meta( $post_id, '_cwpai_woo_redirect_url', esc_attr( $woocommerce_text_field ) );
}
add_action( 'woocommerce_thankyou', 'cwpai_woo_redirectcustom');
function cwpai_woo_redirectcustom( $order_id ){
    $order = new WC_Order( $order_id );
    $items = $order->get_items();
    foreach ( $items as $item ) {
        $product_name = $item['name'];
        $product_id = $item['product_id'];
        $product_variation_id = $item['variation_id'];
    }
    $redirect = get_post_meta( $product_id, '_cwpai_woo_redirect_url', true );
    if ( ! empty( $redirect ) ) {
        wp_redirect( $redirect );
        exit;
    }
}

Dynamic Lead Time For WooCommerce

This code is part of a custom functionality added to a WooCommerce store, which is an e-commerce plugin for WordPress. The code adds a "lead time" feature to certain products within a specific product category.

The first function adds a banner displaying the lead time on the product page for products in the specific category. This helps customers know how long it will take for their order to arrive.

The second and third functions update the lead time for each product in an order when its status changes. This feature allows store owners to adjust the lead time for their products based on order volume and delivery times.

PHP
add_action( 'woocommerce_single_product_summary', 'cwpai_woo_add_lead_time_banner', 5 );
function cwpai_woo_add_lead_time_banner() {
    global $product;
    $product_id = $product->get_id();
    $product_cats = wp_get_post_terms( $product_id, 'product_cat' );
    $product_cat_ids = array();
    foreach ( $product_cats as $product_cat ) {
        $product_cat_ids[] = $product_cat->term_id;
    }
    if ( in_array( 17, $product_cat_ids ) ) {
        $lead_time = get_term_meta( 17, 'lead_time', true );
        if ( ! $lead_time ) {
            $lead_time = 5;
        }
        echo '<div class="lead-time-banner"><p>Lead time: ' . $lead_time . ' days</p></div>';
    }
}
add_action( 'woocommerce_order_status_processing', 'cwpai_woo_update_lead_time' );
function cwpai_woo_update_lead_time( $order_id ) {
    $order = wc_get_order( $order_id );
    $items = $order->get_items();
    foreach ( $items as $item ) {
        $product_id = $item->get_product_id();
        $product_cats = wp_get_post_terms( $product_id, 'product_cat' );
        $product_cat_ids = array();
        foreach ( $product_cats as $product_cat ) {
            $product_cat_ids[] = $product_cat->term_id;
        }
        if ( in_array( 17, $product_cat_ids ) ) {
            $lead_time = get_term_meta( 17, 'lead_time', true );
            if ( ! $lead_time ) {
                $lead_time = 5;
            }
            $lead_time = $lead_time * 1.2;
            if ( $lead_time < 5 ) {
                $lead_time = 5;
            }
            update_term_meta( 17, 'lead_time', $lead_time );
        }
    }
}
add_action( 'woocommerce_order_status_completed', 'cwpai_woo_update_lead_time_completed' );
function cwpai_woo_update_lead_time_completed( $order_id ) {
    $order = wc_get_order( $order_id );
    $items = $order->get_items();
    foreach ( $items as $item ) {
        $product_id = $item->get_product_id();
        $product_cats = wp_get_post_terms( $product_id, 'product_cat' );
        $product_cat_ids = array();
        foreach ( $product_cats as $product_cat ) {
            $product_cat_ids[] = $product_cat->term_id;
        }
        if ( in_array( 17, $product_cat_ids ) ) {
            $lead_time = get_term_meta( 17, 'lead_time', true );
            if ( ! $lead_time ) {
                $lead_time = 5;
            }
            $lead_time = $lead_time / 1.2;
            if ( $lead_time < 5 ) {
                $lead_time = 5;
            }
            update_term_meta( 17, 'lead_time', $lead_time );
        }
    }
}

Min/Max Quantities Snippet

This code snippet adds the functionality of defining minimum and maximum quantities for product variations and validates the quantity of the product added to the cart against these fields.

It addresses a subfeature that's included in Min/Max Quantities, which costs $29.00/yr.

PHP
add_action( 'woocommerce_product_after_variable_attributes', 'cwpai_woo_variation_settings_fields', 10, 3 );
function cwpai_woo_variation_settings_fields( $loop, $variation_data, $variation ) {
    $min_qty = get_post_meta( $variation->ID, 'min_qty', true );
    $max_qty = get_post_meta( $variation->ID, 'max_qty', true );
    ?>
    <div>
        <p class="form-row form-row-first">
            <label><?php esc_html_e( 'Minimum Quantity', 'cwpai' ); ?></label>
            <input type="number" class="short" size="5" name="min_qty[<?php echo $loop; ?>]" value="<?php echo esc_attr( $min_qty ); ?>" />
        </p>
        <p class="form-row form-row-last">
            <label><?php esc_html_e( 'Maximum Quantity', 'cwpai' ); ?></label>
            <input type="number" class="short" size="5" name="max_qty[<?php echo $loop; ?>]" value="<?php echo esc_attr( $max_qty ); ?>" />
        </p>
    </div>
    <?php
}

add_action( 'woocommerce_save_product_variation', 'cwpai_woo_save_variation_settings_fields', 10, 2 );
function cwpai_woo_save_variation_settings_fields( $variation_id, $i ) {
    $min_qty = $_POST['min_qty'][$i];
    $max_qty = $_POST['max_qty'][$i];
    if ( isset( $min_qty ) ) {
        update_post_meta( $variation_id, 'min_qty', esc_attr( $min_qty ) );
    }
    if ( isset( $max_qty ) ) {
        update_post_meta( $variation_id, 'max_qty', esc_attr( $max_qty ) );
    }
}

add_filter( 'woocommerce_add_to_cart_validation', 'cwpai_woo_validate_min_max_quantity', 10, 5 );
function cwpai_woo_validate_min_max_quantity( $passed, $product_id, $quantity, $variation_id = '', $variations = '' ) {
    if ( $variation_id ) {
        $min_qty = get_post_meta( $variation_id, 'min_qty', true );
        $max_qty = get_post_meta( $variation_id, 'max_qty', true );
        if ( $min_qty && $quantity < $min_qty ) {
            wc_add_notice( sprintf( __( 'You must add at least %s of this product to your cart.', 'cwpai' ), $min_qty ), 'error' );
            $passed = false;
        }
        if ( $max_qty && $quantity > $max_qty ) {
            wc_add_notice( sprintf( __( 'You can add a maximum of %s of this product to your cart.', 'cwpai' ), $max_qty ), 'error' );
            $passed = false;
        }
    }
    return $passed;
}

The code achieves this by adding two custom fields for minimum and maximum quantities to the variation form in the WooCommerce product edit screen and saving the values of these fields for each variation. When a product is added to the cart, the code checks if the selected quantity is within the specified range of minimum and maximum quantities for the selected variation. If the quantity is not within the range, an error notice is displayed and the product is not added to the cart.

Custom Add To Cart Redirect (Global and Product Options)

Redirect users to whatever URL you want after clicking on the Add To Cart Button. You can redirect to an internal upsell page, another product, or even an External URL!

Support for Global, Product and Variation-specific redirects.

PHP
class CwpaiAtcRedirect {
    public function __construct() {
        add_action( 'woocommerce_add_to_cart', array( $this, 'cwpai_redirect_to_highest_priority_url' ), 10, 6 );
        add_filter( 'woocommerce_general_settings', array( $this, 'cwpai_add_global_redirect_field' ) );
        add_action( 'woocommerce_product_options_advanced', array( $this, 'cwpai_add_product_redirect_field' ) );
        add_action( 'woocommerce_save_product_variation', array( $this, 'cwpai_save_variation_redirect_field' ), 10, 2 );
        add_action( 'woocommerce_product_after_variable_attributes', array( $this, 'cwpai_add_variation_redirect_field' ), 10, 3 );
    }

    public function cwpai_redirect_to_highest_priority_url( $cart_item_key, $product_id, $quantity, $variation_id = '', $variation = '', $cart_item_data = array() ) {
        $redirect_url = '';
        if ( $variation_id ) {
            $redirect_url = get_post_meta( $variation_id, 'cwpai_variation_redirect_url', true );
        }
        if ( ! $redirect_url ) {
            $redirect_url = get_post_meta( $product_id, 'cwpai_product_redirect_url', true );
        }
        if ( ! $redirect_url ) {
            $redirect_url = get_option( 'cwpai_global_redirect_url' );
        }
        if ( $redirect_url ) {
            wp_redirect( $redirect_url );
            exit;
        }
    }

    public function cwpai_add_global_redirect_field( $settings ) {
        $updated_settings = array();
        foreach ( $settings as $section ) {
            $updated_settings[] = $section;
            if ( isset( $section['id'] ) && 'general_options' == $section['id'] && isset( $section['type'] ) && 'sectionend' == $section['type'] ) {
                $updated_settings[] = array(
                    'name'     => 'Global CWPAI Redirect',
                    'desc_tip' => 'true',
                    'id'       => 'cwpai_global_redirect_url',
                    'type'     => 'text',
                    'css'      => 'min-width:300px;',
                );
            }
        }
        return $updated_settings;
    }

    public function cwpai_add_product_redirect_field() {
        woocommerce_wp_text_input(
            array(
                'id'          => 'cwpai_product_redirect_url',
                'label'       => 'Product CWPAI Redirect',
                'desc_tip'    => 'true',
                'description' => 'Enter the URL to redirect to when this product is added to the cart.',
                'wrapper_class' => 'form-field-wide',
            )
        );
    }

    public function cwpai_save_variation_redirect_field( $variation_id, $i ) {
        $variation_redirect_url = $_POST['cwpai_variation_redirect_url'][$i];
        if ( ! empty( $variation_redirect_url ) ) {
            update_post_meta( $variation_id, 'cwpai_variation_redirect_url', esc_url_raw( $variation_redirect_url ) );
        } else {
            delete_post_meta( $variation_id, 'cwpai_variation_redirect_url' );
        }
    }

    public function cwpai_add_variation_redirect_field( $loop, $variation_data, $variation ) {
        woocommerce_wp_text_input(
            array(
                'id'          => 'cwpai_variation_redirect_url[' . $loop . ']',
                'label'       => 'Variation CWPAI Redirect',
                'desc_tip'    => 'true',
                'description' => 'Enter the URL to redirect to when this variation is added to the cart.',
                'value'       => get_post_meta( $variation->ID, 'cwpai_variation_redirect_url', true ),
                'wrapper_class' => 'form-row form-row-full',
            )
        );
    }
}
new CwpaiAtcRedirect();

Intended to replace this $29 WooCommerce Plugin.

Code snippets for WooCommerce Cart/Checkout Notices

It's easy to generate snippets to create conditional WooCommerce cart checkout notices, a functionality that can replace this $49/yr plugin.

PHP
add_action( 'woocommerce_before_cart', 'cwpai_woo_cod_cart_notice' );
add_action( 'woocommerce_before_checkout_form', 'cwpai_woo_cod_cart_notice' );
function cwpai_woo_cod_cart_notice() {
    if ( WC()->cart->get_cart_contents_count() < 5 && WC()->session->get( 'chosen_payment_method' ) === 'cod' ) {
        wc_print_notice( 'You must have at least 5 items in your cart to use COD payment method.', 'notice' );
    }
}

This is a block of code that adds a custom notice message to the WooCommerce cart and checkout pages when a user attempts to use the "Cash on Delivery" payment method but has less than 5 items in their cart.

PHP
add_action( 'woocommerce_before_cart', 'cwpai_woo_cart_checkout_notice' );
add_action( 'woocommerce_before_checkout_form', 'cwpai_woo_cart_checkout_notice' );
function cwpai_woo_cart_checkout_notice() {
    $cart_total = WC()->cart->get_cart_contents_total();
    $cart_count = WC()->cart->get_cart_contents_count();
    $shipping_country = WC()->customer->get_shipping_country();
    $billing_country = WC()->customer->get_billing_country();
    if ( $cart_total >= 100 || $cart_count >= 5 ) {
        if ( $shipping_country == 'US' && $billing_country == 'AU' ) {
            echo '<div class="woocommerce-message">You qualify for free shipping!</div>';
        }
    }
}

This is another block of code that adds a custom notice message to the WooCommerce cart and checkout pages, this time for users who qualify for free shipping based on certain conditions.

PHP
add_action( 'woocommerce_check_cart_items', 'cwpai_check_cart_items' );
function cwpai_check_cart_items() {
    $product_id = 36;
    $min_quantity = 2;
    $cart_items = WC()->cart->get_cart();
    $quantity = 0;
    foreach ( $cart_items as $cart_item ) {
        if ( $cart_item['product_id'] == $product_id ) {
            $quantity += $cart_item['quantity'];
        }
    }
    if ( $quantity < $min_quantity ) {
        wc_add_notice( sprintf( 'You must have at least %d of product id %d in your cart. <a href="#" class="cwpai-add-items" data-product-id="%d">Add Items</a>', $min_quantity, $product_id, $product_id ), 'error' );
        add_action( 'wp_footer', 'cwpai_add_items_script' );
    }
}

function cwpai_add_items_script() {
    ?>
    <script>
        jQuery(document).ready(function($) {
            $('.cwpai-add-items').on('click', function(e) {
                e.preventDefault();
                var product_id = $(this).data('product-id');
                $.ajax({
                    url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
                    type: 'POST',
                    data: {
                        action: 'cwpai_add_items',
                        product_id: product_id
                    },
                    success: function(response) {
                        window.location.href = '<?php echo wc_get_checkout_url(); ?>';
                    }
                });
            });
        });
    </script>
    <?php
}

add_action( 'wp_ajax_cwpai_add_items', 'cwpai_add_items' );
add_action( 'wp_ajax_nopriv_cwpai_add_items', 'cwpai_add_items' );
function cwpai_add_items() {
    $product_id = $_POST['product_id'];
    $min_quantity = 2;
    WC()->cart->add_to_cart( $product_id, $min_quantity );
    wc_add_notice( 'Items added to cart successfully.', 'success' );
    wp_die();
}

This code checks if the user has added a specific product (identified by its ID) to the cart and has added a minimum quantity of that product. If not, it displays an error notice and allows the user to add more of that product to the cart through an AJAX call.

Conditional Shipping and Payments

This code adds a filter to the "woocommerce_available_payment_gateways" hook in WordPress, which allows you to modify the available payment gateways in WooCommerce based on certain conditions.

It's pretty easy to add conditional shipping and payments using CodeWP, replacing the need for the $79/yr extension "Conditional Shipping and Payments" if you can live without the GUI.

PHP
add_filter( 'woocommerce_available_payment_gateways', 'cwpai_woo_cash_on_demand_payment_method' );
function cwpai_woo_cash_on_demand_payment_method( $available_gateways ) {
    $cart_items = WC()->cart->get_cart();
    $only_product_id_31 = true;
    foreach ( $cart_items as $cart_item ) {
        if ( $cart_item['product_id'] != 31 ) {
            $only_product_id_31 = false;
            break;
        }
    }
    if ( $only_product_id_31 ) {
        $available_gateways['cod'] = $available_gateways['cash_on_demand'];
    } else {
        unset( $available_gateways['cash_on_demand'] );
    }
    return $available_gateways;
}

The function "cwpai_woo_cash_on_demand_payment_method" accepts the currently available gateways as a parameter and returns an updated array of available gateways.

Within the function, it checks if the cart contains only a specific product with ID 31. If it does, it adds the "cod" gateway (which is an alias for "cash_on_demand") to the available gateways array. Otherwise, it removes the "cash_on_demand" gateway from the available gateways array.

This code essentially allows you to limit the payment options available to customers based on the contents of their cart. If their cart only contains the specific product with ID 31, they will be able to choose the "cash on demand" payment option, but if their cart contains any other products, that option will not be available to them.

Premium WordPress Plugins VS These Snippets

Code snippets like these are generally smaller in scope and are designed to add or modify specific functionality in an existing system, whereas fully featured plugins are usually designed to provide more comprehensive functionality or create new features from scratch.

Fully featured plugins can have a range of features and options, and often include user interfaces, settings pages, and advanced functionality. They may also be designed to be compatible with multiple versions of WordPress and other plugins, and may include comprehensive documentation and support.

In contrast, code snippets like the ones provided are generally smaller in scope and may only be intended to perform one specific task or modify one aspect of the system. They may also be more technical in nature, and require a greater understanding of the underlying code and architecture of the system in question.

While plugins may provide a more comprehensive solution, code snippets can be a more lightweight and flexible option for developers looking to add or modify specific functionality in their WordPress site. Furthermore, they're also free, and easy to extend by reusing the prompts in CodeWP or using our handy Edit mode.

Conclusion

WooCommerce is a powerful e-commerce platform that can be extended through various plugins to add more features and functionality. However, these plugins can come at a cost, with prices ranging from $29.00/yr to $49.00/yr. In this article, we have provided several code snippets that fulfill the core functionality of some popular WooCommerce plugins, allowing online store owners to save money while still providing a great customer experience.

While these code snippets may not be as full-featured as their premium plugin counterparts, they offer a cost-effective solution for small businesses and individuals looking to build a successful online store.

CodeWP's robust WooCommerce-oriented AI mode was used to generate all of these snippets. Sign up today, for free, to begin making generations of your own.

About The Author
James LePage
Founder & CEO
More By James LePage
James LePage is an entrepreneur and founder of CodeWP, an AI platform for WordPress creators. With nearly a decade of experience founding startups and leading development agencies, James is focused on leveraging AI research and natural language processing to build smart solutions that make WordPress website creation efficient. As founder of CodeWP, James is dedicated to eliminating tedious developer searches and expensive hiring so anyone can build complex WordPress solutions easily. His technical expertise and passion for innovation drive CodeWP’s mission to serve WordPress creators globally with advanced AI capabilities.
More
Tags
WooCommerce

More Reading

Make WordPress Easy With AI
© WPAI, Inc. 2024 | d.b.a CodeWP