Untitled

 avatar
webwizards
plain_text
15 days ago
2.8 kB
12
Indexable
<?php
/**
 * B2BKing pricing display fixes for WPC Smart Grouped Products (woosg).
 *
 * Makes woosg show B2BKing group prices instead of B2C prices for:
 *   1a. Individual item price on the single product page.
 *   1b. Regular price (so woosg doesn't render group price as a strikethrough sale).
 *   2.  Shop/grid total price for grouped products (sum of selected items).
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Apply B2BKing's group/individual pricing to a given product + price.
 * Returns the B2BKing-adjusted price (regular or sale), or the original if B2BKing is inactive.
 */
function b2bking_woosg_get_price( $price, $product, $type = 'regular' ) {
	if ( ! class_exists( 'B2bking_Public' ) ) {
		return $price;
	}

	static $b2bking_public = null;
	if ( $b2bking_public === null ) {
		$b2bking_public = new B2bking_Public();
	}

	if ( $type === 'sale' ) {
		$adjusted = $b2bking_public->b2bking_individual_pricing_discount_sale_price( $price, $product );
	} else {
		$adjusted = $b2bking_public->b2bking_individual_pricing_fixed_price( $price, $product );
	}

	return $adjusted !== '' && $adjusted !== null ? $adjusted : $price;
}


/**
 * Fix 1a: Individual item price on the single product page.
 */
add_filter(
	'woosg_item_price',
	function ( $price, $product ) {
		return b2bking_woosg_get_price( $price, $product, 'sale' );
	},
	99,
	2
);


/**
 * Fix 1b: Regular price for individual items.
 * Prevents woosg from rendering the group price as a strikethrough sale.
 */
add_filter(
	'woosg_item_regular_price',
	function ( $price, $product ) {
		return b2bking_woosg_get_price( $price, $product, 'regular' );
	},
	99,
	2
);


/**
 * Fix 2: Shop/grid price for grouped (woosg) products.
 * Sums B2BKing group prices across selected child items (qty > 0).
 */
add_filter(
	'woocommerce_get_price_html',
	function ( $price_html, $product ) {
		if ( ! $product->is_type( 'woosg' ) ) {
			return $price_html;
		}

		if ( ! class_exists( 'B2bking_Public' ) ) {
			return $price_html;
		}

		$items = $product->get_items();
		if ( empty( $items ) ) {
			return $price_html;
		}

		$total      = 0;
		$has_b2b    = false;

		foreach ( $items as $item ) {
			$child = wc_get_product( $item['id'] ?? 0 );
			if ( ! $child ) {
				continue;
			}

			$qty = isset( $item['qty'] ) ? (float) $item['qty'] : 0;
			if ( $qty <= 0 ) {
				continue;
			}

			$base_price = (float) $child->get_price();
			$b2b_price  = (float) b2bking_woosg_get_price( $base_price, $child, 'sale' );

			if ( $b2b_price > 0 && $b2b_price !== $base_price ) {
				$has_b2b = true;
			}

			$total += ( $b2b_price > 0 ? $b2b_price : $base_price ) * $qty;
		}

		if ( ! $has_b2b || $total <= 0 ) {
			return $price_html;
		}

		return 'Velkoobchodní cena: ' . wc_price( $total ) . $product->get_price_suffix();
	},
	100,
	2
);
Editor is loading...
Leave a Comment