Code woocomerse upseling plugin
- User
Code woocomerse upseling plugin
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Code woocomerse upseling plugin
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
I'll help you create a WooCommerce upselling plugin. Here's a complete plugin structure with key functionality:
<?php
/**
* Plugin Name: WooCommerce Advanced Upselling
* Description: Advanced upselling functionality for WooCommerce
* Version: 1.0.0
* Author: Your Name
* Requires at least: 5.0
* Tested up to: 6.4
* WC requires at least: 5.0
* WC tested up to: 8.0
*/
// Prevent direct access
if (!defined('ABSPATH')) {
exit;
}
// Check if WooCommerce is active
if (!in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
return;
}
class WC_Upselling_Plugin {
public function __construct() {
add_action('init', array($this, 'init'));
register_activation_hook(__FILE__, array($this, 'activate'));
register_deactivation_hook(__FILE__, array($this, 'deactivate'));
}
public function init() {
// Load plugin textdomain
load_plugin_textdomain('wc-upselling', false, dirname(plugin_basename(__FILE__)) . '/languages');
// Initialize hooks
$this->init_hooks();
// Load admin functionality
if (is_admin()) {
$this->load_admin();
}
}
private function init_hooks() {
// Add upsell popup to cart page
add_action('woocommerce_after_cart_table', array($this, 'display_cart_upsells'));
// Add upsells to checkout page
add_action('woocommerce_checkout_before_order_review', array($this, 'display_checkout_upsells'));
// AJAX handlers
add_action('wp_ajax_add_upsell_to_cart', array($this, 'ajax_add_upsell_to_cart'));
add_action('wp_ajax_nopriv_add_upsell_to_cart', array($this, 'ajax_add_upsell_to_cart'));
// Enqueue scripts
add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
// Add upsells after add to cart
add_filter('woocommerce_add_to_cart_fragments', array($this, 'upsell_fragments'));
}
public function enqueue_scripts() {
if (is_cart() || is_checkout() || is_shop() || is_product()) {
wp_enqueue_script(
'wc-upselling-js',
plugin_dir_url(__FILE__) . 'assets/js/upselling.js',
array('jquery'),
'1.0.0',
true
);
wp_enqueue_style(
'wc-upselling-css',
plugin_dir_url(__FILE__) . 'assets/css/upselling.css',
array(),
'1.0.0'
);
wp_localize_script('wc-upselling-js', 'wc_upselling_ajax', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('wc_upselling_nonce')
));
}
}
public function display_cart_upsells() {
$cart_items = WC()->cart->get_cart();
$upsell_products = $this->get_upsell_products($cart_items);
if (!empty($upsell_products)) {
$this->render_upsell_section($upsell_products, 'cart');
}
}
public function display_checkout_upsells() {
$cart_items = WC()->cart->get_cart();
$upsell_products = $this->get_upsell_products($cart_items);
if (!empty($upsell_products)) {
$this->render_upsell_section($upsell_products, 'checkout');
}
}
private function get_upsell_products($cart_items) {
$upsell_products = array();
$cart_product_ids = array();
// Get all product IDs in cart
foreach ($cart_items as $cart_item) {
$cart_product_ids[] = $cart_item['product_id'];
}
// Get upsells for each cart item
foreach ($cart_items as $cart_item) {
$product = wc_get_product($cart_item['product_id']);
if ($product) {
$upsells = $product->get_upsell_ids();
foreach ($upsells as $upsell_id) {
// Don't suggest products already in cart
if (!in_array($upsell_id, $cart_product_ids) && !in_array($upsell_id, $upsell_products)) {
$upsell_product = wc_get_product($upsell_id);
if ($upsell_product && $upsell_product->is_purchasable()) {
$upsell_products[] = $upsell_id;
}
}
}
}
}
// Limit to 3 upsells
return array_slice($upsell_products, 0, 3);
}
private function render_upsell_section($upsell_products, $location) {
?>
<div class="wc-upselling-section" data-location="<?php echo esc_attr($location); ?>">
<h3><?php _e('You might also like', 'wc-upselling'); ?></h3>
<div class="upsell-products-grid">
<?php foreach ($upsell_products as $product_id): ?>
<?php $this->render_upsell_product($product_id); ?>
<?php endforeach; ?>
</div>
</div>
<?php
}
private function render_upsell_product($product_id) {
$product = wc_get_product($product_id);
if (!$product) return;
?>
<div class="upsell-product" data-product-id="<?php echo esc_attr($product_id); ?>">
<div class="upsell-product-image">
<?php echo $product->get_image('thumbnail'); ?>
</div>
<div class="upsell-product-details">
<h4 class="upsell-product-title"><?php echo $product->get_name(); ?></h4>
<div class="upsell-product-price">
<?php echo $product->get_price_html(); ?>
</div>
<button class="button add-upsell-to-cart" data-product-id="<?php echo esc_attr($product_id); ?>">
<?php _e('Add to Cart', 'wc-upselling'); ?>
</button>
</div>
</div>
<?php
}
public function ajax_add_upsell_to_cart() {
check_ajax_referer('wc_upselling_nonce', 'nonce');
$product_id = intval($_POST['product_id']);
$quantity = isset($_POST['quantity']) ? intval($_POST['quantity']) : 1;
$result = WC()->cart->add_to_cart($product_id, $quantity);
if ($result) {
wp_send_json_success(array(
'message' => __('Product added to cart!', 'wc-upselling'),
'cart_count' => WC()->cart->get_cart_contents_count()
));
} else {
wp_send_json_error(array(
'message' => __('Failed to add product to cart.', 'wc-upselling')
));
}
}
public function upsell_fragments($fragments) {
ob_start();
?>
<span class="cart-count"><?php echo WC()->cart->get_cart_contents_count(); ?></span>
<?php
$fragments['.cart-count'] = ob_get_clean();
return $fragments;
}
private function load_admin() {
include_once plugin_dir_path(__FILE__) . 'includes/admin.php';
new WC_Upselling_Admin();
}
public function activate() {
// Create database tables if needed
$this->create_tables();
}
public function deactivate() {
// Cleanup if needed
}
private function create_tables() {
global $wpdb;
$table_name = $wpdb->prefix . 'wc_upselling_stats';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
product_id mediumint(9) NOT NULL,
upsell_product_id mediumint(9) NOT NULL,
conversion_count mediumint(9) DEFAULT 0,
view_count mediumint(9) DEFAULT 0,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY product_id (product_id),
KEY upsell_product_id (upsell_product_id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
}
// Initialize the plugin
new WC_Upselling_Plugin();
jQuery(document).ready(function($) {
// Handle upsell add to cart
$('.add-upsell-to-cart').on('click', function(e) {
e.preventDefault();
var $button = $(this);
var productId = $button.data('product-id');
$button.prop('disabled', true).text('Adding...');
$.ajax({
url: wc_upselling_ajax.ajax_url,
type: 'POST',
data: {
action: 'add_upsell_to_cart',
product_id: productId,
quantity: 1,
nonce: wc_upselling_ajax.nonce
},
success: function(response) {
if (response.success) {
$button.text('Added!').addClass('added');
// Update cart count if element exists
if ($('.cart-count').length) {
$('.cart-count').text(response.data.cart_count);
}
// Show success message
showUpsellMessage(response.data.message, 'success');
// Hide the upsell product after adding
$button.closest('.upsell-product').fadeOut();
} else {
$button.prop('disabled', false).text('Add to Cart');
showUpsellMessage(response.data.message, 'error');
}
},
error: function() {
$button.prop('disabled', false).text('Add to Cart');
showUpsellMessage('Something went wrong. Please try again.', 'error');
}
});
});
function showUpsellMessage(message, type) {
var messageClass = type === 'success' ? 'wc-upsell-success' : 'wc-upsell-error';
var $message = $('<div class="wc-upsell-message ' + messageClass + '">' + message + '</div>');
$('.wc-upselling-section').prepend($message);
setTimeout(function() {
$message.fadeOut(function() {
$(this).remove();
});
}, 3000);
}
// Track upsell views for analytics
$('.upsell-product').each(function() {
var productId = $(this).data('product-id');
// You can add view tracking here
});
});
.wc-upselling-section {
margin: 20px 0;
padding: 20px;
border: 1px solid #ddd;
border-radius: 5px;
background: #f9f9f9;
}
.wc-upselling-section h3 {
margin-top: 0;
margin-bottom: 15px;
color: #333;
}
.upsell-products-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 15px;
}
.upsell-product {
background: white;
border: 1px solid #e0e0e0;
border-radius: 5px;
padding: 15px;
text-align: center;
transition: box-shadow 0.3s ease;
}
.upsell-product:hover {
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.upsell-product-image img {
max-width: 100%;
height: auto;
border-radius: 3px;
}
.upsell-product-title {
font-size: 14px;
margin: 10px 0 5px;
line-height: 1.4;
}
.upsell-product-price {
font-weight: bold;
color: #333;
margin-bottom: 10px;
}
.add-upsell-to-cart {
background: #0073aa;
color: white;
border: none;
padding: 8px 16px;
border-radius: 3px;
cursor: pointer;
transition: background 0.3s ease;
}
.add-upsell-to-cart:hover {
background: #005a87;
}
.add-upsell-to-cart:disabled {
background: #ccc;
cursor: not-allowed;
}
.add-upsell-to-cart.added {
background: #46b450;
}
.wc-upsell-message {
padding: 10px;
margin-bottom: 15px;
border-radius: 3px;
}
.wc-upsell-success {
background: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.wc-upsell-error {
background: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
@media (max-width: 768px) {
.upsell-products-grid {
grid-template-columns: 1fr;
}
}
<?php
class WC_Upselling_Admin {
public function __construct() {
add_action('admin_menu', array($this, 'add_admin_menu'));
add_action('add_meta_boxes', array($this, 'add_product_meta_boxes'));
add_action('save_post', array($this, 'save_product_meta'));