Introduce vendor names along with standard labels across shipping packages
define("PV_ATTRIBUTE", "vendor");
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
/**
* Check if WooCommerce is active
*/
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
if ( ! class_exists( 'TH_Shipping_Options' ) ) {
class TH_Shipping_Options {
/**
* Constructor for your shipping class
*
* @access public
* @return void
*/
public function __construct() {
// take care of anything else that needs to be done immediately upon plugin instantiation, here in the constructor.
add_filter( 'woocommerce_cart_shipping_packages', array( &$this, 'th_woocommerce_cart_shipping_packages') );
// Overriding template to introduce vendor names along with standard labels across shipping packages.
//add_filter( 'woocommerce_locate_template', array( $this, 'th_woocommerce_locate_template' ), 10, 3 );
}
function th_woocommerce_locate_template( $template, $template_name, $template_path ) {
if('cart/cart-shipping.php' == $template_name)
{
$path = plugin_dir_path( __FILE__ ) . '/woocommerce/templates/' . $template_name;
return file_exists( $path ) ? $path : $template;
}
return $template;
}
function th_woocommerce_cart_shipping_packages( $packages ) {
// Reset the packages
$packages = array();
$vendor_items_map = array();
foreach ( WC()->cart->get_cart() as $item ) {
$product_id = $item['product_id'];
$vendors = get_product_vendors( $product_id );
if ( $item['data']->needs_shipping() ) {
if($vendors) {
foreach( $vendors as $vendor ) {
// Expecting/assuming there is only one Vendor assigned per product. Hm.
$vendor_items_map[$vendor->ID][] = $item;
break;
}
}
// No product vendor associated with item.
else {
$vendor_items_map['0'][] = $item;
}
}
}
foreach($vendor_items_map as $key => $vendor_items) {
$packages[] = array(
//'ship_via' => array( 'flat_rate' ),
'contents' => $vendor_items,
'contents_cost' => array_sum( wp_list_pluck( $vendor_items, 'line_total' ) ),
'applied_coupons' => WC()->cart->applied_coupons,
'destination' => array(
'country' => WC()->customer->get_shipping_country(),
'state' => WC()->customer->get_shipping_state(),
'postcode' => WC()->customer->get_shipping_postcode(),
'city' => WC()->customer->get_shipping_city(),
'address' => WC()->customer->get_shipping_address(),
'address_2' => WC()->customer->get_shipping_address_2()
)
);
}
return $packages;
}
}
// finally instantiate our plugin class and add it to the set of globals
$GLOBALS['th_shipping_options_init'] = new TH_Shipping_Options();
}
// Start up this plugin
add_action( 'init', 'TH_Shipping_Options' );
function TH_Shipping_Options() {
global $TH_Shipping_Options;
$TH_Shipping_Options = new TH_Shipping_Options();
}
}