hook_position();
add_shortcode( 'abqd_table', array( $this, 'shortcode' ) );
add_shortcode( 'qdt_table', array( $this, 'shortcode' ) ); // Backward-compatible alias.
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_assets' ) );
add_action( 'admin_enqueue_scripts', array( $this, 'admin_assets' ) );
add_action( 'woocommerce_before_mini_cart', array( $this, 'reset_mini' ) );
add_action( 'woocommerce_widget_shopping_cart_before_buttons', array( $this, 'mini_cart_notice' ) );
add_action( 'woocommerce_after_mini_cart', array( $this, 'mini_cart_notice' ) );
add_action( 'wc_ajax_abqd_mini', array( $this, 'ajax_mini' ) );
}
/* ---------------------------------------------------------------
* Settings
* ------------------------------------------------------------- */
private function settings() {
$defaults = array(
'enabled' => 'yes',
'tiers' => array(
array( 'min' => 2, 'max' => 2, 'percent' => 5 ),
array( 'min' => 3, 'max' => 4, 'percent' => 10 ),
array( 'min' => 5, 'max' => 0, 'percent' => 15 ),
),
'count_mode' => 'product', // product = all variations combined, variation = each separately.
'exclude_sale' => 'no',
'cats' => array(),
'show_table' => 'yes',
'position' => 'after_form',
'show_notice' => 'yes',
'show_minicart'=> 'yes',
'notice_text' => __( 'Add {qty} more eligible {items} to unlock {percent}% off.', 'ab-qty-discount' ),
'max_text' => __( "You've unlocked the maximum {percent}% off!", 'ab-qty-discount' ),
'notice_color' => '#2e9e5b',
);
$saved = get_option( self::OPT, null );
if ( null === $saved ) {
$saved = get_option( 'qdt_settings', array() ); // Settings from the pre-release version.
}
$saved = is_array( $saved ) ? $saved : array();
$s = wp_parse_args( $saved, $defaults );
$design = ( isset( $saved['design'] ) && is_array( $saved['design'] ) ) ? $saved['design'] : array();
if ( ! isset( $design['n_bg'] ) && ! empty( $saved['notice_color'] ) ) {
$design['n_bg'] = $saved['notice_color']; // migrate from v1.0 setting.
}
$s['design'] = wp_parse_args( $design, $this->design_defaults() );
return $s;
}
private function save_settings() {
$mins = isset( $_POST['qdt_min'] ) ? (array) wp_unslash( $_POST['qdt_min'] ) : array();
$maxs = isset( $_POST['qdt_max'] ) ? (array) wp_unslash( $_POST['qdt_max'] ) : array();
$pcts = isset( $_POST['qdt_pct'] ) ? (array) wp_unslash( $_POST['qdt_pct'] ) : array();
$tiers = array();
foreach ( $mins as $i => $m ) {
$min = absint( $m );
$max = absint( isset( $maxs[ $i ] ) ? $maxs[ $i ] : 0 );
$pct = isset( $pcts[ $i ] ) ? (float) str_replace( ',', '.', sanitize_text_field( $pcts[ $i ] ) ) : 0;
if ( $min < 1 || $pct <= 0 ) {
continue;
}
if ( $max && $max < $min ) {
$max = $min;
}
$tiers[] = array(
'min' => $min,
'max' => $max,
'percent' => min( 100, round( $pct, 2 ) ),
);
}
usort( $tiers, function ( $a, $b ) {
return $a['min'] <=> $b['min'];
} );
$cats = isset( $_POST['qdt_cats'] ) ? array_map( 'absint', (array) wp_unslash( $_POST['qdt_cats'] ) ) : array();
$position = isset( $_POST['qdt_position'] ) ? sanitize_key( wp_unslash( $_POST['qdt_position'] ) ) : 'after_form';
$notice_text = isset( $_POST['qdt_notice_text'] ) ? sanitize_text_field( wp_unslash( $_POST['qdt_notice_text'] ) ) : '';
$max_text = isset( $_POST['qdt_max_text'] ) ? sanitize_text_field( wp_unslash( $_POST['qdt_max_text'] ) ) : '';
$design = $this->clean_design( isset( $_POST['qdt_d'] ) ? (array) wp_unslash( $_POST['qdt_d'] ) : array(), isset( $_POST['qdt_reset_design'] ) );
$count_mode = isset( $_POST['qdt_count_mode'] ) ? sanitize_key( wp_unslash( $_POST['qdt_count_mode'] ) ) : 'product';
$clean = array(
'enabled' => isset( $_POST['qdt_enabled'] ) ? 'yes' : 'no',
'tiers' => $tiers,
'count_mode' => 'variation' === $count_mode ? 'variation' : 'product',
'exclude_sale' => isset( $_POST['qdt_exclude_sale'] ) ? 'yes' : 'no',
'cats' => array_values( array_filter( $cats ) ),
'show_table' => isset( $_POST['qdt_show_table'] ) ? 'yes' : 'no',
'position' => array_key_exists( $position, $this->positions() ) ? $position : 'after_form',
'show_notice' => isset( $_POST['qdt_show_notice'] ) ? 'yes' : 'no',
'show_minicart'=> isset( $_POST['qdt_show_minicart'] ) ? 'yes' : 'no',
'notice_text' => '' !== $notice_text ? $notice_text : __( 'Add {qty} more eligible {items} to unlock {percent}% off.', 'ab-qty-discount' ),
'max_text' => '' !== $max_text ? $max_text : __( "You've unlocked the maximum {percent}% off!", 'ab-qty-discount' ),
'notice_color' => $design['n_bg'],
'design' => $design,
);
update_option( self::OPT, $clean );
}
/* ---------------------------------------------------------------
* Core logic
* ------------------------------------------------------------- */
private function eligible( $product_id, $s ) {
if ( empty( $s['cats'] ) ) {
return true;
}
return has_term( array_map( 'intval', $s['cats'] ), 'product_cat', $product_id );
}
private function tier_for( $qty, $s ) {
$pct = 0;
foreach ( $s['tiers'] as $t ) {
if ( $qty >= $t['min'] && ( 0 === (int) $t['max'] || $qty <= $t['max'] ) ) {
$pct = (float) $t['percent'];
break;
}
}
return $pct;
}
public function apply( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
$s = $this->settings();
if ( 'yes' !== $s['enabled'] || empty( $s['tiers'] ) ) {
return;
}
// Count quantities.
$counts = array();
foreach ( $cart->get_cart() as $item ) {
$pid = (int) $item['product_id'];
$key = ( 'variation' === $s['count_mode'] && ! empty( $item['variation_id'] ) ) ? (int) $item['variation_id'] : $pid;
$counts[ $key ] = ( isset( $counts[ $key ] ) ? $counts[ $key ] : 0 ) + (int) $item['quantity'];
}
foreach ( $cart->get_cart() as $cart_key => $item ) {
unset( $cart->cart_contents[ $cart_key ]['qdt_pct'], $cart->cart_contents[ $cart_key ]['qdt_orig'] );
$pid = (int) $item['product_id'];
$vid = (int) $item['variation_id'];
$fresh = wc_get_product( $vid ? $vid : $pid );
if ( ! $fresh ) {
continue;
}
// Always start from the real price so discounts never compound.
$orig = (float) $fresh->get_price();
$item['data']->set_price( $orig );
if ( ! $this->eligible( $pid, $s ) ) {
continue;
}
if ( 'yes' === $s['exclude_sale'] && $fresh->is_on_sale() ) {
continue;
}
$ck = ( 'variation' === $s['count_mode'] && $vid ) ? $vid : $pid;
$pct = $this->tier_for( isset( $counts[ $ck ] ) ? $counts[ $ck ] : 0, $s );
if ( $pct <= 0 ) {
continue;
}
$new = round( $orig * ( 1 - $pct / 100 ), wc_get_price_decimals() );
$item['data']->set_price( $new );
$cart->cart_contents[ $cart_key ]['qdt_pct'] = $pct;
$cart->cart_contents[ $cart_key ]['qdt_orig'] = $orig;
}
}
public function cart_price( $price_html, $cart_item, $cart_item_key ) {
if ( empty( $cart_item['qdt_pct'] ) ) {
return $price_html;
}
$orig = wc_price( wc_get_price_to_display( $cart_item['data'], array( 'price' => $cart_item['qdt_orig'] ) ) );
/* translators: %s: discount percentage value */
$badge = sprintf(
esc_html__( '(%s%% off)', 'ab-qty-discount' ),
esc_html( (float) $cart_item['qdt_pct'] )
);
return '' . $orig . ' ' . $price_html . ' ' . $badge . '';
}
/* ---------------------------------------------------------------
* Design options
* ------------------------------------------------------------- */
private function design_fields() {
$weights = array( '400', '500', '600', '700', '800' );
return array(
// Table.
'font_family' => array( 'group' => 'table', 'label' => __( 'Font family', 'ab-qty-discount' ), 'type' => 'font', 'default' => '', 'var' => '--qdt-font', 'unit' => '' ),
'font_size' => array( 'group' => 'table', 'label' => __( 'Table text size', 'ab-qty-discount' ), 'type' => 'number', 'default' => 14, 'min' => 10, 'max' => 30, 'var' => '--qdt-fs', 'unit' => 'px' ),
'title_color' => array( 'group' => 'table', 'label' => __( 'Title color', 'ab-qty-discount' ), 'type' => 'color', 'default' => '#222222', 'var' => '--qdt-title-c', 'unit' => '' ),
'title_size' => array( 'group' => 'table', 'label' => __( 'Title size', 'ab-qty-discount' ), 'type' => 'number', 'default' => 16, 'min' => 10, 'max' => 40, 'var' => '--qdt-title-fs', 'unit' => 'px' ),
'title_weight' => array( 'group' => 'table', 'label' => __( 'Title weight', 'ab-qty-discount' ), 'type' => 'select', 'default' => '600', 'options' => $weights, 'var' => '--qdt-title-fw', 'unit' => '' ),
'th_bg' => array( 'group' => 'table', 'label' => __( 'Header background', 'ab-qty-discount' ), 'type' => 'color', 'default' => '#f6f6f6', 'var' => '--qdt-th-bg', 'unit' => '' ),
'th_color' => array( 'group' => 'table', 'label' => __( 'Header text color', 'ab-qty-discount' ), 'type' => 'color', 'default' => '#222222', 'var' => '--qdt-th-c', 'unit' => '' ),
'td_bg' => array( 'group' => 'table', 'label' => __( 'Row background', 'ab-qty-discount' ), 'type' => 'color', 'default' => '#ffffff', 'var' => '--qdt-td-bg', 'unit' => '' ),
'td_color' => array( 'group' => 'table', 'label' => __( 'Row text color', 'ab-qty-discount' ), 'type' => 'color', 'default' => '#333333', 'var' => '--qdt-td-c', 'unit' => '' ),
'b_color' => array( 'group' => 'table', 'label' => __( 'Border color', 'ab-qty-discount' ), 'type' => 'color', 'default' => '#dddddd', 'var' => '--qdt-b-c', 'unit' => '' ),
'b_width' => array( 'group' => 'table', 'label' => __( 'Border width', 'ab-qty-discount' ), 'type' => 'number', 'default' => 1, 'min' => 0, 'max' => 10, 'var' => '--qdt-b-w', 'unit' => 'px' ),
'b_radius' => array( 'group' => 'table', 'label' => __( 'Border radius', 'ab-qty-discount' ), 'type' => 'number', 'default' => 6, 'min' => 0, 'max' => 40, 'var' => '--qdt-b-r', 'unit' => 'px' ),
// Notice.
'n_bg' => array( 'group' => 'notice', 'label' => __( 'Background color', 'ab-qty-discount' ), 'type' => 'color', 'default' => '#2e9e5b', 'var' => '--qdt-n-bg', 'unit' => '' ),
'n_color' => array( 'group' => 'notice', 'label' => __( 'Text color', 'ab-qty-discount' ), 'type' => 'color', 'default' => '#ffffff', 'var' => '--qdt-n-c', 'unit' => '' ),
'n_bar' => array( 'group' => 'notice', 'label' => __( 'Progress bar color', 'ab-qty-discount' ), 'type' => 'color', 'default' => '#ffffff', 'var' => '--qdt-bar', 'unit' => '' ),
'n_size' => array( 'group' => 'notice', 'label' => __( 'Text size', 'ab-qty-discount' ), 'type' => 'number', 'default' => 14, 'min' => 10, 'max' => 30, 'var' => '--qdt-n-fs', 'unit' => 'px' ),
'n_weight' => array( 'group' => 'notice', 'label' => __( 'Text weight', 'ab-qty-discount' ), 'type' => 'select', 'default' => '400', 'options' => $weights, 'var' => '--qdt-n-fw', 'unit' => '' ),
'n_bc' => array( 'group' => 'notice', 'label' => __( 'Border color', 'ab-qty-discount' ), 'type' => 'color', 'default' => '#1f7a46', 'var' => '--qdt-n-bc', 'unit' => '' ),
'n_bw' => array( 'group' => 'notice', 'label' => __( 'Border width', 'ab-qty-discount' ), 'type' => 'number', 'default' => 0, 'min' => 0, 'max' => 10, 'var' => '--qdt-n-bw', 'unit' => 'px' ),
'n_radius' => array( 'group' => 'notice', 'label' => __( 'Border radius', 'ab-qty-discount' ), 'type' => 'number', 'default' => 6, 'min' => 0, 'max' => 40, 'var' => '--qdt-n-r', 'unit' => 'px' ),
);
}
private function design_defaults() {
$out = array();
foreach ( $this->design_fields() as $k => $f ) {
$out[ $k ] = $f['default'];
}
return $out;
}
private function clean_design( $post, $reset = false ) {
$out = array();
foreach ( $this->design_fields() as $k => $f ) {
$v = ( ! $reset && isset( $post[ $k ] ) && ! is_array( $post[ $k ] ) ) ? $post[ $k ] : $f['default'];
switch ( $f['type'] ) {
case 'color':
$c = sanitize_hex_color( (string) $v );
$out[ $k ] = $c ? $c : $f['default'];
break;
case 'number':
$out[ $k ] = max( $f['min'], min( $f['max'], (int) $v ) );
break;
case 'select':
$out[ $k ] = in_array( (string) $v, $f['options'], true ) ? (string) $v : $f['default'];
break;
default: // font.
$v = preg_replace( '/[^A-Za-z0-9 ,\-"\'_]/', '', (string) $v );
$out[ $k ] = substr( trim( $v ), 0, 120 );
}
}
return $out;
}
/* ---------------------------------------------------------------
* Table position
* ------------------------------------------------------------- */
private function positions() {
return array(
'after_form' => __( 'Below Add to cart (default)', 'ab-qty-discount' ),
'before_form' => __( 'Above Add to cart', 'ab-qty-discount' ),
'beside' => __( 'Beside Add to cart (right side on desktop, below on mobile)', 'ab-qty-discount' ),
'shortcode' => __( 'Custom: only where I place the [abqd_table] shortcode', 'ab-qty-discount' ),
);
}
private function hook_position() {
$s = $this->settings();
$map = array(
'after_form' => 'woocommerce_after_add_to_cart_form',
'before_form' => 'woocommerce_before_add_to_cart_form',
'beside' => 'woocommerce_after_add_to_cart_button',
);
if ( isset( $map[ $s['position'] ] ) ) {
add_action( $map[ $s['position'] ], array( $this, 'render_table' ) );
}
}
/* ---------------------------------------------------------------
* Progress notice (product page + mini cart)
* ------------------------------------------------------------- */
public function enqueue_assets() {
$s = $this->settings();
if ( 'yes' !== $s['enabled'] ) {
return;
}
wp_enqueue_style( 'abqd-style', plugin_dir_url( __FILE__ ) . 'assets/css/abqd.css', array(), self::VERSION );
wp_add_inline_style( 'abqd-style', $this->css_vars( $s ) );
if ( 'yes' === $s['show_minicart'] && ! empty( $s['tiers'] ) ) {
wp_enqueue_script( 'abqd-frontend', plugin_dir_url( __FILE__ ) . 'assets/js/frontend.js', array(), self::VERSION, true );
wp_add_inline_script(
'abqd-frontend',
'window.abqdFrontend = ' . wp_json_encode(
array(
'ajaxUrl' => add_query_arg( 'wc-ajax', 'abqd_mini', home_url( '/' ) ),
'nonce' => wp_create_nonce( 'abqd_mini' ),
)
) . ';',
'before'
);
}
}
public function admin_assets() {
$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
if ( 'ab-qty-discount' !== $page ) {
return;
}
$s = $this->settings();
wp_enqueue_style( 'abqd-admin', plugin_dir_url( __FILE__ ) . 'assets/css/abqd.css', array(), self::VERSION );
wp_add_inline_style( 'abqd-admin', $this->css_vars( $s ) );
wp_enqueue_script( 'abqd-admin', plugin_dir_url( __FILE__ ) . 'assets/js/admin.js', array(), self::VERSION, true );
wp_add_inline_script(
'abqd-admin',
'window.abqdAdmin = ' . wp_json_encode(
array(
'rowTemplate' => $this->row_html( '', '', '' ),
)
) . ';',
'before'
);
}
private function css_vars( $s ) {
$fields = $this->design_fields();
$vars = '';
foreach ( $fields as $k => $f ) {
$raw = isset( $s['design'][ $k ] ) ? $s['design'][ $k ] : $f['default'];
switch ( $f['type'] ) {
case 'color':
$sanitized = sanitize_hex_color( (string) $raw );
if ( ! $sanitized ) {
$sanitized = sanitize_hex_color( (string) $f['default'] );
}
$value = $sanitized ? $sanitized : '#000000';
break;
case 'number':
$value = (string) max( (int) $f['min'], min( (int) $f['max'], absint( $raw ) ) );
break;
case 'select':
$value = in_array( (string) $raw, $f['options'], true ) ? (string) $raw : (string) $f['default'];
break;
default: // font family.
$cleaned = preg_replace( '/[^A-Za-z0-9 ,\-"\'_]/', '', (string) $raw );
$cleaned = substr( trim( $cleaned ), 0, 120 );
$value = '' !== $cleaned ? $cleaned : 'inherit';
break;
}
// CSS custom property variable name comes from our own design_fields() definition,
// not from user input, so it is inherently trusted. The unit is also hard-coded.
$vars .= $f['var'] . ':' . $value . $f['unit'] . ';';
}
return ':root{' . $vars . '}';
}
private function cart_groups( $s ) {
$groups = array();
if ( ! function_exists( 'WC' ) || ! WC()->cart ) {
return $groups;
}
foreach ( WC()->cart->get_cart() as $item ) {
$pid = (int) $item['product_id'];
$vid = (int) $item['variation_id'];
$key = ( 'variation' === $s['count_mode'] && $vid ) ? $vid : $pid;
if ( ! isset( $groups[ $key ] ) ) {
$groups[ $key ] = array(
'pid' => $pid,
'qty' => 0,
'name' => ( 'variation' === $s['count_mode'] && $vid ) ? $item['data']->get_name() : get_the_title( $pid ),
'sale' => $item['data']->is_on_sale(),
);
}
$groups[ $key ]['qty'] += (int) $item['quantity'];
}
return $groups;
}
private function next_step( $qty, $s ) {
foreach ( $s['tiers'] as $t ) {
if ( (int) $t['min'] > $qty ) {
return array(
'type' => 'next',
'need' => (int) $t['min'] - $qty,
'percent' => (float) $t['percent'],
'progress' => $qty / (int) $t['min'] * 100,
);
}
}
$cur = $this->tier_for( $qty, $s );
if ( $cur > 0 ) {
return array( 'type' => 'max', 'percent' => $cur, 'progress' => 100 );
}
return null;
}
private function notice_html( $qty, $s, $name = '' ) {
$step = $this->next_step( $qty, $s );
if ( ! $step ) {
return '';
}
if ( 'next' === $step['type'] ) {
$msg = str_replace(
array( '{qty}', '{items}', '{percent}' ),
array( (int) $step['need'], _n( 'item', 'items', (int) $step['need'], 'ab-qty-discount' ), (float) $step['percent'] ),
$s['notice_text']
);
} else {
$msg = str_replace( '{percent}', (float) $step['percent'], $s['max_text'] );
}
$progress_pct = absint( round( $step['progress'] ) );
if ( $progress_pct > 100 ) {
$progress_pct = 100;
}
return '
| ' . esc_html__( 'Quantity', 'ab-qty-discount' ) . ' | ' . esc_html__( 'Discount', 'ab-qty-discount' ) . ' |
|---|
' . esc_html__( 'Settings saved.', 'ab-qty-discount' ) . '