mandatory_cart_min.php

mandatory_cart_min.php

The provided PHP code creates a WordPress plugin, WooCommerce Mandatory Cart Minimum, which allows you to enforce a minimum cart total for WooCommerce checkout. This plugin adds an admin settings page where you can specify the minimum cart value. This is done using object-oriented programming (OOP) principles and WordPress hooks and functions. The plugin uses the 'woocommerce_check_cart_items' action hook to validate the cart total before checkout. If the cart total is less than the specified minimum, an error notice is added, and the checkout process is halted.

<?php /* Plugin Name: WooCommerce Mandatory Cart Minimum Description: Enforces a minimum cart total for WooCommerce checkout. Version: 1.0 Author: CodeWP */ if (!defined('ABSPATH')) exit; class WC_Mandatory_Cart_Minimum { private $option_name = 'wc_mandatory_cart_minimum'; public function __construct() { add_action('admin_menu', array($this, 'add_admin_menu')); add_action('admin_init', array($this, 'register_settings')); add_action('woocommerce_check_cart_items', array($this, 'validate_cart_minimum')); } public function add_admin_menu() { add_options_page( 'WooCommerce Mandatory Cart Minimum', 'WC Cart Minimum', 'manage_options', $this->option_name, array($this, 'create_settings_page') ); } public function register_settings() { register_setting($this->option_name, $this->option_name, 'intval'); } public function create_settings_page() { ?> <div class="wrap"> <form method="post" action="options.php"> <?php settings_fields($this->option_name); do_settings_sections($this->option_name); $minimum = get_option($this->option_name, 0); ?> <table class="form-table"> <tr valign="top"> <th scope="row">Minimum Cart Total</th> <td><input type="number" name="<?php echo $this->option_name; ?>" value="<?php echo $minimum; ?>" /></td> </tr> </table> <?php submit_button(); ?> </form> </div> <?php } public function validate_cart_minimum() { $minimum = get_option($this->option_name, 0); if (WC()->cart->total < $minimum) { wc_add_notice(sprintf('Your current cart total is %s — you must have an order with a minimum of %s to place your order.', wc_price(WC()->cart->total), wc_price($minimum)), 'error'); } } } new WC_Mandatory_Cart_Minimum();

Frequently Asked Questions

This plugin enforces a minimum cart total requirement before customers can proceed with the WooCommerce checkout process. It helps maintain a minimum order value for purchases.