Home / eCommerce / Get Wholesale Price Array For A Product Based On A Wholesale Role
Duplicate Snippet

Embed Snippet on Your Site

Get Wholesale Price Array For A Product Based On A Wholesale Role

Code Preview
php
<?php
/**
 * Class that handles wholesale price HTML generation and display.
 *
 * @since 1.0.0
 */
class WWP_Wholesale_Price_HTML_Handler {
    /**
     * Model that houses the logic of retrieving information relating to wholesale role/s of a user.
     *
     * @since  1.5.0
     * @access private
     * @var WWP_Wholesale_Roles
     */
    private $_wwp_wholesale_roles;
    /**
     * WWP_Wholesale_Price_HTML_Handler constructor.
     *
     * @param array $dependencies Array of instance objects of all dependencies.
     *
     * @since  1.0.0
     * @access public
     */
    public function __construct( $dependencies = array() ) {
    }
    /**
     * Return product raw wholesale price for a given wholesale user role.
     *
     * @param int   $product_id          Product id.
     * @param array $user_wholesale_role Array of user wholesale roles.
     *
     * @since  1.5.0
     * @access public
     *
     * @return string Raw wholesale price.
     */
    public static function get_product_raw_wholesale_price( $product_id, $user_wholesale_role ) {
        // Get product object.
        $product = wc_get_product( $product_id );
        // check if valid product.
        if ( ! is_a( $product, 'WC_Product' ) ) {
            return '';
        }
        if ( empty( $user_wholesale_role ) ) {
            $wholesale_price = '';
        } elseif ( WWP_ACS_Integration_Helper::aelia_currency_switcher_active() ) {
            $wholesale_price            = $product->get_meta( $user_wholesale_role[0] . '_wholesale_price', true );
            $baseCurrencyWholesalePrice = $wholesale_price;
            if ( $baseCurrencyWholesalePrice ) {
                $activeCurrency = get_woocommerce_currency();
                $baseCurrency   = WWP_ACS_Integration_Helper::get_product_base_currency( $product_id );
                if ( $activeCurrency === $baseCurrency ) {
                    $wholesale_price = $baseCurrencyWholesalePrice;
                } else { // Base Currency.
                    $wholesale_price = $product->get_meta( $user_wholesale_role[0] . '_' . $activeCurrency . '_wholesale_price', true );
                    if ( ! $wholesale_price ) {
                        /**
                         * This specific currency has no explicit wholesale price (Auto). Therefore will need to convert the wholesale price
                         * set on the base currency to this specific currency.
                         *
                         * This is why it is very important users set the wholesale price for the base currency if they want wholesale pricing
                         * to work properly with aelia currency switcher plugin integration.
                         */
                        $wholesale_price = WWP_ACS_Integration_Helper::convert( $baseCurrencyWholesalePrice, $activeCurrency, $baseCurrency );
                    }
                }
                $wholesale_price = apply_filters( 'wwp_filter_' . $activeCurrency . '_wholesale_price', $wholesale_price, $product_id, $user_wholesale_role );
            } else {
                $wholesale_price = '';
            }
            // Base currency not set. Ignore the rest of the wholesale price set on other currencies.
        } else {
            $wholesale_price = $product->get_meta( $user_wholesale_role[0] . '_wholesale_price', true );
        }
        /**
         * Allows to filter the raw wholesale price for a product.
         *
         * @param string     $wholesale_price     The raw product wholesale price.
         * @param WC_Product $product             The product object.
         * @param array      $user_wholesale_role The user wholesale roles.
         */
        return apply_filters(
            'wwp_get_product_raw_wholesale_price',
            $wholesale_price,
            $product,
            $user_wholesale_role
        );
    }
    /**
     * Return product wholesale price for a given wholesale user role.
     * With 'wwp_filter_wholesale_price_shop' filter already applied.
     * The wholesale price returned is passed through taxing filters.
     *
     * @param int   $product_id          Product id.
     * @param array $user_wholesale_role Array of user wholesale roles.
     *
     * @since  1.6.0 Refactor codebase.
     * @since  1.12 Compatibility with "WooCommerce Currency Switcher by PluginUs.NET. Woo Multi Currency and Woo Multi
     *         Pay" plugin
     *
     * @access public
     *
     * @return array Array containing wholesale price data.
     */
    public static function get_product_wholesale_price_on_shop_v3( $product_id, $user_wholesale_role ) {
        $price_arr  = array();
        $user_id    = apply_filters( 'wwp_wholesale_price_current_user_id', get_current_user_id() );
        $product    = wc_get_product( $product_id );
        $cache_data = apply_filters( 'wwp_get_product_wholesale_price_on_shop_v3_cache', false, $user_id, $product, $product_id, $user_wholesale_role );
        if ( ! empty( $cache_data ) ) {
            $price_arr = $cache_data;
        } else {
            $per_product_level_wholesale_price = self::get_product_raw_wholesale_price( $product_id, $user_wholesale_role );
            if ( empty( $per_product_level_wholesale_price ) ) {
                $result = apply_filters(
                    'wwp_filter_wholesale_price_shop',
                    array(
                        'source'          => 'per_product_level',
                        'wholesale_price' => $per_product_level_wholesale_price,
                    ),
                    $product_id,
                    $user_wholesale_role,
                    null,
                    null
                );
                $price_arr['wholesale_price_raw'] = trim( $result['wholesale_price'] );
                $price_arr['source']              = $result['source'];
            } else {
                $price_arr['wholesale_price_raw'] = $per_product_level_wholesale_price;
                $price_arr['source']              = 'per_product_level';
            }
            // Single Product Page Wholesale Price "WooCommerce Currency Switcher" plugin support
            // "WooCommerce Currency Switcher" must be enabled and "Aelia Currency Switcher for WooCommerce" must be disabled.
            if (
                WWP_Helper_Functions::is_plugin_active( 'woocommerce-currency-switcher/index.php' ) &&
                ! WWP_Helper_Functions::is_plugin_active( 'woocommerce-aelia-currencyswitcher/woocommerce-aelia-currencyswitcher.php' )
            ) {
                if ( ! empty( $price_arr['wholesale_price_raw'] ) && 'per_product_level' === $price_arr['source'] ) {
                    $price_arr['wholesale_price_raw'] = apply_filters( 'woocommerce_product_get_price', $price_arr['wholesale_price_raw'], $product );
                }
            }
            $price_arr['wholesale_price'] = trim( apply_filters( 'wwp_pass_wholesale_price_through_taxing', $price_arr['wholesale_price_raw'], $product_id, $user_wholesale_role ) );
            // when product price is inclusive of tax, we use the calculated wholesale_price here cause it has been deducted by tax.
            if ( wc_prices_include_tax() && $price_arr['wholesale_price_raw'] ) {
                $price_arr['wholesale_price_with_no_tax'] = WWP_Helper_Functions::wwp_get_price_excluding_tax(
                    $product,
                    array(
                        'qty'   => 1,
                        'price' => $price_arr['wholesale_price_raw'],
                    )
                );
            } else {
                $price_arr['wholesale_price_with_no_tax'] = $price_arr['wholesale_price_raw'];
            }
            $price_arr['wholesale_price_with_tax'] = WWP_Helper_Functions::wwp_get_price_including_tax(
                $product,
                array(
                    'qty'   => 1,
                    'price' => $price_arr['wholesale_price_raw'],
                )
            );
            if ( isset( $price_arr['wholesale_price'] ) && $price_arr['wholesale_price'] > 0 ) {
                do_action( 'wwp_after_get_product_wholesale_price_on_shop_v3', $user_id, $product, $product_id, $user_wholesale_role, $price_arr );
            }
        }
        return apply_filters( 'wwp_filter_wholesale_price_shop_v2', $price_arr, $product_id, $user_wholesale_role );
    }
    /**
     * Return wholesale price suffix.
     *
     * @param WC_Product $product                     Product object.
     * @param array      $user_wholesale_role         User's wholesale role.
     * @param string     $wholesale_price             Wholesale price.
     * @param boolean    $return_wholesale_price_only Whether to only return the wholesale price markup.
     * @param array      $extra_args                  Extra arguments.
     *
     * @since  1.5.0
     * @access public
     *
     * @return string Wholesale price suffix.
     */
    public static function get_wholesale_price_suffix(
        $product,
        $user_wholesale_role,
        $wholesale_price,
        $return_wholesale_price_only = false,
        $extra_args = array()
    ) {
        $wc_price_suffix = apply_filters( 'wwp_wholesale_price_suffix', get_option( 'woocommerce_price_display_suffix' ) );
        if ( ! empty( $user_wholesale_role ) ) {
            $price_arr  = self::get_product_wholesale_price_on_shop_v3( WWP_Helper_Functions::wwp_get_product_id( $product ), $user_wholesale_role );
            $base_price = apply_filters( 'wwp_wholesale_price_suffix_base_price', ! empty( $price_arr['wholesale_price_raw'] ) ? $price_arr['wholesale_price_raw'] : $product->get_regular_price(), $product );
            // To be used in function get_wholesale_price_display_suffix_filter of WWPP
            // For wholesale price display suffix.
            $extra_args['base_price'] = $base_price;
            if ( strpos( $wc_price_suffix, '{price_including_tax}' ) !== false ) {
                $wholesale_price_incl_tax = WWP_Helper_Functions::wwp_formatted_price(
                    WWP_Helper_Functions::wwp_get_price_including_tax(
                        $product,
                        array(
                            'qty'   => 1,
                            'price' => $base_price,
                        )
                    )
                );
                $wc_price_suffix          = str_replace( '{price_including_tax}', $wholesale_price_incl_tax, $wc_price_suffix );
            }
            if ( strpos( $wc_price_suffix, '{price_excluding_tax}' ) !== false ) {
                $wholesale_price_excl_tax = WWP_Helper_Functions::wwp_formatted_price(
                    WWP_Helper_Functions::wwp_get_price_excluding_tax(
                        $product,
                        array(
                            'qty'   => 1,
                            'price' => $base_price,
                        )
                    )
                );
                $wc_price_suffix          = str_replace( '{price_excluding_tax}', $wholesale_price_excl_tax, $wc_price_suffix );
            }
            $wc_price_suffix = ' <small class="woocommerce-price-suffix wholesale-price-suffix">' . $wc_price_suffix . '</small>';
        } else {
            $wc_price_suffix = $product->get_price_suffix();
        }
        return apply_filters( 'wwp_filter_wholesale_price_display_suffix', $wc_price_suffix, $product, $user_wholesale_role, $wholesale_price, $return_wholesale_price_only, $extra_args );
    }
    /**
     * Filter callback that alters the product price, it embeds the wholesale price of a product for a wholesale user.
     *
     * @param string     $price                       Product price in html.
     * @param WC_Product $product                     WC_Product instance.
     * @param array      $user_wholesale_role         User's wholesale role.
     * @param boolean    $return_wholesale_price_only Whether to only return the wholesale price markup. Used for
     *                                                products cpt listing.
     *
     * @since  1.0.0
     * @since  1.2.8 Now if empty $price then don't bother creating wholesale html price.
     * @since  1.5.0 Refactor codebase.
     * @since  1.6.0 Refactor codebase.
     * @access public
     *
     * @return string Product price with wholesale applied if necessary.
     */
    public static function wholesale_price_html_filter( $price, $product, $user_wholesale_role = null, $return_wholesale_price_only = false ) {
        if ( ! empty( $user_wholesale_role ) && ! empty( $price ) ) {
            $wholesale_price_title_text = trim( apply_filters( 'wwp_filter_wholesale_price_title_text', __( 'Wholesale Price:', 'woocommerce-wholesale-prices' ) ) );
            $raw_wholesale_price        = '';
            $wholesale_price            = '';
            $source                     = '';
            $extra_args                 = array();
            if ( in_array(
                WWP_Helper_Functions::wwp_get_product_type( $product ),
                array(
                    'simple',
                    'variation',
                ),
                true
            ) ) {
                $price_arr           = self::get_product_wholesale_price_on_shop_v3( WWP_Helper_Functions::wwp_get_product_id( $product ), $user_wholesale_role );
                $raw_wholesale_price = $price_arr['wholesale_price'];
                $source              = $price_arr['source'];
                if ( strcasecmp( $raw_wholesale_price, '' ) !== 0 ) {
                    $wholesale_price = WWP_Helper_Functions::wwp_formatted_price( $raw_wholesale_price );
                    if ( ! $return_wholesale_price_only ) {
                        $wholesale_price .= self::get_wholesale_price_suffix( $product, $user_wholesale_role, $price_arr['wholesale_price_with_no_tax'], $return_wholesale_price_only );
                    }
                }
            } elseif ( WWP_Helper_Functions::wwp_get_product_type( $product ) === 'variable' ) {
                $user_id    = apply_filters( 'wwp_wholesale_price_current_user_id', get_current_user_id() );
                $cache_data = apply_filters( 'wwp_get_variable_product_price_range_cache', false, $user_id, $product, $user_wholesale_role );
                // Do not use caching if $return_wholesale_price_only is true, coz this is used on cpt listing
                // and cpt listing callback is triggered unpredictably, and multiple times.
                // It is even triggered even before WC have initialized.
                if ( is_array( $cache_data ) && $cache_data['min_price'] && $cache_data['max_price'] && ! $return_wholesale_price_only ) {
                    $min_price                            = $cache_data['min_price'];
                    $min_wholesale_price_without_taxing   = $cache_data['min_wholesale_price_without_taxing'];
                    $max_price                            = $cache_data['max_price'];
                    $max_wholesale_price_without_taxing   = $cache_data['max_wholesale_price_without_taxing'];
                    $some_variations_have_wholesale_price = $cache_data['some_variations_have_wholesale_price'];
                } else {
                    $variations                           = $product->get_children();
                    $min_price                            = '';
                    $min_wholesale_price_without_taxing   = '';
                    $max_price                            = '';
                    $max_wholesale_price_without_taxing   = '';
                    $some_variations_have_wholesale_price = false;
                    foreach ( $variations as $variation_id ) {
                        $variation = wc_get_product( $variation_id );
                        if ( ! $variation || ! $variation->is_purchasable() ) {
                            continue;
                        }
                        $curr_var_price = wc_get_price_to_display( $variation );
                        $price_arr      = self::get_product_wholesale_price_on_shop_v3( $variation_id, $user_wholesale_role );
                        if ( strcasecmp( $price_arr['wholesale_price'], '' ) !== 0 ) {
                            $curr_var_price = $price_arr['wholesale_price'];
                            if ( ! $some_variations_have_wholesale_price ) {
                                $some_variations_have_wholesale_price = true;
                            }
                        }
                        if ( strcasecmp( $min_price, '' ) === 0 || $curr_var_price < $min_price ) {
                            $min_price                          = $curr_var_price;
                            $min_wholesale_price_without_taxing = strcasecmp( $price_arr['wholesale_price_with_no_tax'], '' ) !== 0 ? $price_arr['wholesale_price_with_no_tax'] : '';
                        }
                        if ( strcasecmp( $max_price, '' ) === 0 || $curr_var_price > $max_price ) {
                            $max_price                          = $curr_var_price;
                            $max_wholesale_price_without_taxing = strcasecmp( $price_arr['wholesale_price_with_no_tax'], '' ) !== 0 ? $price_arr['wholesale_price_with_no_tax'] : '';
                        }
                    }
                    if ( ! $return_wholesale_price_only ) {
                        do_action(
                            'wwp_after_variable_product_compute_price_range',
                            $user_id,
                            $product,
                            $user_wholesale_role,
                            array(
                                'min_price' => $min_price,
                                'min_wholesale_price_without_taxing' => $min_wholesale_price_without_taxing,
                                'max_price' => $max_price,
                                'max_wholesale_price_without_taxing' => $max_wholesale_price_without_taxing,
                                'some_variations_have_wholesale_price' => $some_variations_have_wholesale_price,
                            )
                        );
                    }
                }
                // To be used in function get_wholesale_price_display_suffix_filter of WWPP
                // For wholesale price display suffix.
                $extra_args = array(
                    'min_price' => $min_price,
                    'max_price' => $max_price,
                );
                // Only alter price html if, some/all variations of this variable product have sale price and
                // min and max price have valid values.
                if ( $some_variations_have_wholesale_price && strcasecmp( $min_price, '' ) !== 0 && strcasecmp( $max_price, '' ) !== 0 ) {
                    if ( $min_price !== $max_price && $min_price < $max_price ) {
                        $wholesale_price = WWP_Helper_Functions::wwp_formatted_price( $min_price ) . ' - ' . WWP_Helper_Functions::wwp_formatted_price( $max_price );
                        $wc_price_suffix = get_option( 'woocommerce_price_display_suffix' );
                        if ( strpos( $wc_price_suffix, '{price_including_tax}' ) === false && strpos( $wc_price_suffix, '{price_excluding_tax}' ) === false && ! $return_wholesale_price_only ) {
                            $wsprice          = ! empty( $max_wholesale_price_without_taxing ) ? $max_wholesale_price_without_taxing : null;
                            $wholesale_price .= self::get_wholesale_price_suffix( $product, $user_wholesale_role, $wsprice, $return_wholesale_price_only, $extra_args );
                        }
                    } else {
                        $wholesale_price = WWP_Helper_Functions::wwp_formatted_price( $max_price );
                        if ( ! $return_wholesale_price_only ) {
                            $wsprice          = ! empty( $max_wholesale_price_without_taxing ) ? $max_wholesale_price_without_taxing : null;
                            $wholesale_price .= self::get_wholesale_price_suffix( $product, $user_wholesale_role, $wsprice, $return_wholesale_price_only, $extra_args );
                        }
                    }
                }
                $return_value = apply_filters(
                    'wwp_filter_variable_product_wholesale_price_range',
                    array(
                        'wholesale_price'             => $wholesale_price,
                        'price'                       => $price,
                        'product'                     => $product,
                        'user_wholesale_role'         => $user_wholesale_role,
                        'min_price'                   => $min_price,
                        'min_wholesale_price_without_taxing' => $min_wholesale_price_without_taxing,
                        'max_price'                   => $max_price,
                        'max_wholesale_price_without_taxing' => $max_wholesale_price_without_taxing,
                        'wholesale_price_title_text'  => $wholesale_price_title_text,
                        'return_wholesale_price_only' => $return_wholesale_price_only,
                    )
                );
                $wholesale_price = $return_value['wholesale_price'];
                if ( isset( $return_value['wholesale_price_title_text'] ) ) {
                    $wholesale_price_title_text = $return_value['wholesale_price_title_text'];
                }
            }
            // Third party plugins can use this filter to alter the wholesale price html before returning wholesale price only.
            $wholesale_price = apply_filters( 'wwp_before_wholesale_price_html_filter', $wholesale_price, $price, $product, $user_wholesale_role, $wholesale_price_title_text, $raw_wholesale_price, $source, $return_wholesale_price_only );
            if ( strcasecmp( $wholesale_price, '' ) !== 0 ) {
                $wholesale_price_html = '<span style="display: block;" class="wholesale_price_container">
                                            <span class="wholesale_price_title">' . $wholesale_price_title_text . '</span>
                                            <ins>' . $wholesale_price . '</ins>
                                        </span>';
                /**
                 * Filter wholesale price html before returning wholesale price only.
                 *
                 * @param string     $wholesale_price_html        The Wholesale price markup.
                 * @param string     $price                       Original product price.
                 * @param WC_Product $product                     Product object.
                 * @param array      $user_wholesale_role         Array of user wholesale roles.
                 * @param string     $wholesale_price_title_text  Wholesale price title text.
                 * @param int|string $raw_wholesale_price         Unformatted wholesale price. Only available for simple & variation products.
                 * @param string     $source                      Source of the wholesale price being applied.
                 * @param boolean    $return_wholesale_price_only Whether to only return the wholesale price markup.
                 * @param string     $wholesale_price             Formatted wholesale price.
                 */
                $wholesale_price_html = apply_filters( 'wwp_filter_wholesale_price_html_before_return_wholesale_price_only', $wholesale_price_html, $price, $product, $user_wholesale_role, $wholesale_price_title_text, $raw_wholesale_price, $source, $return_wholesale_price_only, $wholesale_price );
                if ( $return_wholesale_price_only ) {
                    return $wholesale_price_html;
                }
                $wholesale_price_html = apply_filters( 'wwp_product_original_price', '<del class="original-computed-price">' . $price . '</del>', $wholesale_price, $price, $product, $user_wholesale_role ) . $wholesale_price_html;
                /**
                 * Filter wholesale price html.
                 *
                 * @param string     $wholesale_price_html       The Wholesale price markup.
                 * @param string     $price                      Original product price.
                 * @param WC_Product $product                    Product object.
                 * @param array      $user_wholesale_role        Array of user wholesale roles.
                 * @param string     $wholesale_price_title_text Wholesale price title text.
                 * @param int|string $raw_wholesale_price        Unformatted wholesale price. Only available for simple & variation products.
                 * @param string     $source                     Source of the wholesale price being applied.
                 * @param string     $wholesale_price            Formatted wholesale price.
                 */
                return apply_filters( 'wwp_filter_wholesale_price_html', $wholesale_price_html, $price, $product, $user_wholesale_role, $wholesale_price_title_text, $raw_wholesale_price, $source, $wholesale_price );
            }
        }
        return apply_filters( 'wwp_filter_variable_product_price_range_for_none_wholesale_users', $price, $product );
    }
}
add_action('init', 'initialize_product');
function initialize_product() {
    $product             = wc_get_product( 347 );
    $price_html = WWP_Wholesale_Price_HTML_Handler::wholesale_price_html_filter( 1, $product, array( 'wholesale_customer' ), true );
    preg_match_all('/\d+\.\d+/',  $price_html, $matches);
    if( isset( $matches[0] ) && ! empty( $matches[0] ) ) {
        error_log(print_r($matches[0], 1));
    }
}

Comments

Add a Comment