1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
<?php
namespace SIW\Modules;
use SIW\Elements;
class Menu_Cart {
protected $menu_locations = [
'primary_navigation',
'mobile_navigation'
];
public static function init() {
$self = new self();
add_filter( 'wp_nav_menu_items', [ $self, 'add_cart_to_menu'], 10, 2 );
add_filter( 'woocommerce_add_to_cart_fragments', [ $self, 'update_cart'] );
add_action( 'wp_enqueue_scripts', [ $self, 'enqueue_scripts' ], PHP_INT_MAX );
}
public function add_cart_to_menu( string $items, \stdClass $args ) {
if ( ! in_array( $args->theme_location, $this->menu_locations ) ) {
return $items;
}
$items .= '<li class="menu-item menu-cart">' . $this->render_cart() . '</li>';
return $items;
}
protected function render_cart() {
$cart_count = WC()->cart->get_cart_contents_count();
ob_start();
?>
<a class="siw-cart" href="<?php echo wc_get_cart_url(); ?>" title="<?php esc_attr_e( 'Winkelmand', 'siw') ?>">
<span class="hidden-sm hidden-md hidden-lg"><?php esc_html_e( 'Je winkelmand', 'siw' );?></span>
<?php echo Elements::generate_icon( 'siw-icon-suitcase');?>
<span class="siw-cart-count"><?php echo $cart_count; ?></span>
</a>
<?php
return ob_get_clean();
}
public function update_cart( array $fragments ) {
$cart_count = WC()->cart->get_cart_contents_count();
$fragments['span.siw-cart-count'] = '<span class="siw-cart-count">' . $cart_count . '</span>';
return $fragments;
}
public function enqueue_scripts() {
wp_register_script( 'siw-menu-cart', SIW_ASSETS_URL . 'js/modules/siw-menu-cart.js', [ 'jquery', 'js-cookie' ] , SIW_PLUGIN_VERSION, true );
wp_enqueue_script( 'siw-menu-cart' );
}
}