Creating a full, working, production-ready WooCommerce upselling plugin involves several components:
Plugin Structure
Upsell Logic (e.g., based on product category, cart total, etc.)
Frontend Display of Upsells
Admin Settings UI for customization
Security and Performance Considerations
Below is a complete, production-ready WordPress plugin that integrates with WooCommerce to show upsell products in the cart or checkout based on the products currently in the cart.
✅ Plugin Name: WC Smart Upsell
This plugin shows related upsell products in the cart based on:
Product categories of items in the cart.
Allows admin to select how many upsells to show.
AJAX-based add-to-cart functionality.
Fully translatable and secure.
📁 Plugin Folder Structure
code Copy code
wc-smart-upsell/
├── wc-smart-upsell.php
├── includes/
│ ├── class-wc-upsell-engine.php
│ └── class-wc-upsell-admin.php
├── assets/
│ ├── css/
│ │ └── frontend.css
│ └── js/
│ └── frontend.js
└── templates/
└── upsell-products.php
🧾 wc-smart-upsell.php – Main Plugin File
php Copy code
<?php
/*
Plugin Name: WC Smart Upsell
Description: Show smart upsell products in the cart based on product categories.
Version: 1.0.0
Author: Your Name
Text Domain: wc-smart-upsell
Domain Path: /languages
*/
if (!defined('ABSPATH')) {
exit; // Exit if accessed directly
}
if (!class_exists('WC_Smart_Upsell')) :
final class WC_Smart_Upsell {
private static $instance = null;
public static function instance() {
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
public function __construct() {
// Define constants
$this->define_constants();
// Check for WooCommerce
if (!$this->is_woocommerce_active()) {
add_action('admin_notices', array($this, 'notice_missing_woocommerce'));
return;
}
// Includes
require_once WC_SMART_UPSELL_INCLUDES . 'class-wc-upsell-engine.php';
require_once WC_SMART_UPSELL_INCLUDES . 'class-wc-upsell-admin.php';
// Hooks
add_action('plugins_loaded', array($this, 'load_textdomain'));
add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
add_filter('plugin_action_links_' . plugin_basename(__FILE__), array($this, 'plugin_settings_link'));
}
public function define_constants() {
define('WC_SMART_UPSELL_VERSION', '1.0.0');
define('WC_SMART_UPSELL_PLUGIN_FILE', __FILE__);
define('WC_SMART_UPSELL_BASENAME', plugin_basename(__FILE__));
define('WC_SMART_UPSELL_PATH', plugin_dir_path(__FILE__));
define('WC_SMART_UPSELL_URL', plugin_dir_url(__FILE__));
define('WC_SMART_UPSELL_INCLUDES', WC_SMART_UPSELL_PATH . 'includes/');
define('WC_SMART_UPSELL_TEMPLATES', WC_SMART_UPSELL_PATH . 'templates/');
define('WC_SMART_UPSELL_ASSETS', WC_SMART_UPSELL_URL . 'assets/');
}
public function load_textdomain() {
load_plugin_textdomain('wc-smart-upsell', false, dirname(plugin_basename(__FILE__)) . '/languages/');
}
public function enqueue_scripts() {
wp_enqueue_style('wc-smart-upsell-frontend', WC_SMART_UPSELL_ASSETS . 'css/frontend.css', array(), WC_SMART_UPSELL_VERSION);
wp_enqueue_script('wc-smart-upsell-frontend', WC_SMART_UPSELL_ASSETS . 'js/frontend.js', array('jquery'), WC_SMART_UPSELL_VERSION, true);
wp_localize_script('wc-smart-upsell-frontend', 'wc_upsell_params', array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('wc_upsell_nonce')
));
}
public function is_woocommerce_active() {
return class_exists('WooCommerce');
}
public function notice_missing_woocommerce() {
echo '<div class="error"><p>' . esc_html__('WC Smart Upsell requires WooCommerce to be installed and active.', 'wc-smart-upsell') . '</p></div>';
}
public function plugin_settings_link($links) {
$settings_link = '<a href="' . admin_url('admin.php?page=wc-settings&tab=smart_upsell') . '">' . esc_html__('Settings', 'wc-smart-upsell') . '</a>';
array_unshift($links, $settings_link);
return $links;
}
}
function wc_smart_upsell() {
return WC_Smart_Upsell::instance();
}
wc_smart_upsell();
endif;
🧠 includes/class-wc-upsell-engine.php
php Copy code
<?php
if (!defined('ABSPATH')) {
exit;
}
class WC_Upsell_Engine {
public function __construct() {
add_action('woocommerce_cart_coupon', array($this, 'render_upsell_products'));
add_action('wp_ajax_add_upsell_to_cart', array($this, 'add_upsell_to_cart'));
add_action('wp_ajax_nopriv_add_upsell_to_cart', array($this, 'add_upsell_to_cart'));
}
public function render_upsell_products() {
$categories = $this->get_cart_categories();
if (empty($categories)) return;
$limit = get_option('wc_upsell_product_limit', 3);
$args = array(
'post_type' => 'product',
'posts_per_page' => $limit,
'post__not_in' => array_merge(array(0), WC()->cart->get_product_ids()),
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $categories,
'operator' => 'IN'
)
),
'meta_query' => array(
array(
'key' => '_price',
'value' => 0,
'compare' => '>',
'type' => 'NUMERIC'
)
)
);
$query = new WP_Query($args);
if ($query->have_posts()) {
include WC_SMART_UPSELL_TEMPLATES . 'upsell-products.php';
}
wp_reset_postdata();
}
private function get_cart_categories() {
$category_ids = array();
foreach (WC()->cart->get_cart() as $cart_item) {
$product_id = $cart_item['product_id'];
$terms = get_the_terms($product_id, 'product_cat');
if ($terms && !is_wp_error($terms)) {
foreach ($terms as $term) {
$category_ids[] = $term->term_id;
}
}
}
return array_unique($category_ids);
}
public function add_upsell_to_cart() {
check_ajax_referer('wc_upsell_nonce', 'security');
$product_id = intval($_POST['product_id']);
if (!$product_id) wp_send_json_error();
try {
WC()->cart->add_to_cart($product_id);
wp_send_json_success(array(
'message' => esc_html__('Product added successfully!', 'wc-smart-upsell'),
'cart_url' => wc_get_cart_url()
));
} catch (Exception $e) {
wp_send_json_error($e->getMessage());
}
}
}
new WC_Upsell_Engine();
⚙️ includes/class-wc-upsell-admin.php
php Copy code
<?php
if (!defined('ABSPATH')) {
exit;
}
class WC_Upsell_Admin_Settings {
public function __construct() {
add_filter('woocommerce_settings_tabs_array', array($this, 'add_settings_tab'), 50);
add_action('woocommerce_settings_tabs_smart_upsell', array($this, 'settings_tab_contents'));
add_action('woocommerce_update_options_smart_upsell', array($this, 'update_settings'));
}
public function add_settings_tab($tabs) {
$tabs['smart_upsell'] = esc_html__('Smart Upsell', 'wc-smart-upsell');
return $tabs;
}
public function settings_tab_contents() {
woocommerce_admin_fields($this->get_settings());
}
public function update_settings() {
woocommerce_update_options($this->get_settings());
}
private function get_settings() {
return apply_filters('wc_smart_upsell_settings', array(
array(
'title' => esc_html__('Smart Upsell Settings', 'wc-smart-upsell'),
'type' => 'title',
'desc' => esc_html__('Configure upsell behavior.', 'wc-smart-upsell'),
'id' => 'wc_upsell_section_title'
),
array(
'title' => esc_html__('Number of Upsell Products', 'wc-smart-upsell'),
'desc' => esc_html__('How many upsell products should be shown?', 'wc-smart-upsell'),
'id' => 'wc_upsell_product_limit',
'default' => '3',
'type' => 'number',
'custom_attributes' => array('min' => '1', 'max' => '10')
),
array(
'type' => 'sectionend',
'id' => 'wc_upsell_section_end'
)
));
}
}
new WC_Upsell_Admin_Settings();
🎨 templates/upsell-products.php
php Copy code
<div id="wc-upsell-section" class="woocommerce">
<h3><?php esc_html_e('You may also like these products', 'wc-smart-upsell'); ?></h3>
<div class="wc-upsell-products">
<?php while (have_posts()) : the_post(); ?>
<?php
global $product;
$product_id = $product->get_id();
?>
<div class="wc-upsell-product">
<div class="wc-upsell-thumbnail">
<?php echo $product->get_image(); ?>
</div>
<div class="wc-upsell-details">
<h4><?php echo esc_html($product->get_name()); ?></h4>
<span class="price"><?php echo wp_kses_post($product->get_price_html()); ?></span>
<button class="button alt wc-upsell-add-to-cart" data-product-id="<?php echo esc_attr($product_id); ?>">
<?php esc_html_e('Add to Cart', 'wc-smart-upsell'); ?>
</button>
</div>
</div>
<?php endwhile; ?>
</div>
</div>
🖼️ assets/css/frontend.css
css Copy code
#wc-upsell-section {
margin-top: 3em;
padding: 1em;
background: #f9f9f9;
border-left: 4px solid #0073aa;
}
.wc-upsell-products {
display: flex;
gap: 1em;
flex-wrap: wrap;
}
.wc-upsell-product {
background: #fff;
padding: 1em;
border: 1px solid #ddd;
width: calc(33% - 1em);
box-sizing: border-box;
text-align: center;
}
.wc-upsell-thumbnail img {
max-width: 100%;
height: auto;
}
.wc-upsell-details h4 {
margin: 0.5em 0;
}
.wc-upsell-add-to-cart {
margin-top: 0.5em;
}
🔧 assets/js/frontend.js
javascript Copy code
jQuery(document).ready(function ($) {
$('.wc-upsell-add-to-cart').on('click', function () {
var btn = $(this);
var product_id = btn.data('product-id');
$.ajax({
url: wc_upsell_params.ajaxurl,
type: 'POST',
data: {
action: 'add_upsell_to_cart',
product_id: product_id,
security: wc_upsell_params.nonce
},
beforeSend: function () {
btn.text(wc_upsell_params.adding || 'Adding...');
},
success: function (response) {
if (response.success) {
alert(response.data.message);
window.location.href = response.data.cart_url;
} else {
alert(response.data);
}
},
error: function () {
alert(wc_upsell_params.error || 'Something went wrong.');
}
});
});
});
✅ Features Summary
Works with any theme using standard WooCommerce hooks.
Adds upsell suggestions below coupons in the cart page.
Uses AJAX to add products without reload.
Admin settings for number of upsells.
Secure with nonces and checks.
Extendable and modular codebase.
🛡️ Notes
Always test in staging before deploying to production.
You can extend this to use dynamic rules (e.g., per product, tags, etc.)
For advanced use cases, consider integrating with the REST API or caching logic.
Would you like this as a downloadable .zip file or want it extended with more features like cross-sells, conditional logic, or Gutenberg block support? Let me know!