Learning AMP: Adding WooCommerce Cart Button — AMPire.city

Image for post
Image for post
Originally published at https://ampire.city

What Will I Learn?

Requirements:

Shopping Cart Button in AMP-Friendly Theme Example

PHP/HTML Code

<?php if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
$count = WC()->cart->cart_contents_count; ?>
<a class="cart-contents" href="<?php echo WC()->cart->get_cart_url(); ?>" title="<?php _e( 'View your shopping cart', 'ampire.city' ); ?>">
<?php if ( $count > 0 ) { ?>
<span class="cart-contents-count"><?php echo esc_html( $count ); ?></span>
<?php } ?>
</a>
<?php }; ?>

CSS

.cart-contents:before { 
content: '';
margin-top:8px;
padding-right:5px;
vertical-align: bottom;
width: 24px;
height: 24px;
background:url('../images/cart.svg') no-repeat center center/contain;
display: inline-block;
}
.cart-contents:hover {
text-decoration: none;
}
.cart-contents-count {
color: #fff;
background-color: #2ecc71;
font-weight: bold;
border-radius: 10px;
padding: 1px 6px;
line-height: 1;
font-family: Arial, Helvetica, sans-serif;
vertical-align: top;
}

How it Works

<?php $count = WC()->cart->cart_contents_count; ?>
<a class="cart-contents" href="<?php echo WC()->cart->get_cart_url(); ?>" title="<?php _e( 'View your shopping cart', 'ampire.city' ); ?>">
<?php if ( $count > 0 ) { ?>
<span class="cart-contents-count"><?php echo esc_html( $count ); ?></span>
<?php } ?>
</a>
<?php } ?>
<?php if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) { // Your code } ?>
Image for post
Image for post
As you can see the cart is working, but it requires some styling from the front-end perspective.

Stylizing Cart Button

.cart-contents:before { 
font-family:WooCommerce;
content: "\e01d";
font-size:28px;
margin-top:10px;
font-style:normal;
font-weight:400;
padding-right:5px;
vertical-align: bottom;
}
.cart-contents:hover {
text-decoration: none;
}
.cart-contents-count {
color: #fff;
background-color: #2ecc71;
font-weight: bold;
border-radius: 10px;
padding: 1px 6px;
line-height: 1;
font-family: Arial, Helvetica, sans-serif;
vertical-align: top;
}

Adding Custom Cart Icon

.cart-contents:before { 
content: '';
margin-top:8px;
padding-right:5px;
vertical-align: bottom;
width: 24px;
height: 24px;
background:url('../images/cart.svg') no-repeat center center/contain;
display: inline-block;
}
Image for post
Image for post
As you can see, the shopping cart icon nows blends with the rest of the website’s design.

Developing AMP WooCommerce Website

Travel Blogger, Web Designer & AMP Developer | Travel & History Journal: https://www.ctdots.eu | AMP Development & Web Design Tutorials: https://ampire.city

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store