CMS Woocommerce WordPress

[WooCommerce] Crear tu propio carrito de la compra

[titulo][WooCommerce] Aprende a programar un carrito de WooCommerce para poder personalizarlo 100%[/titulo]

En el siguiente minitutorial de Loopeando.com aprenderemos a crear un carrito como el siguente:

Lo podéis ver en vivo en: https://elperezoso.es

Sus principales caracteristicas son:

  • Marca el número de productos que hay en el carrito, en tiempo real y sin necesidad de hacer clic en él.
  • Al pasar el ratón sobre el icono, se despliega la vista detalle mostrando todos los items que hemos seleccionado.
  • En la lista detalle se muestra el precio total, el precio de cada item y el número de items comprados de cada tipo.
  • Desde la vista detalle podemos: O bien ir al chekout o bien eliminar items directamente sin pasar por el checkout ni por la vista ampliada del carrito.

 

[resumen]
  1. Nuestro código
  2. Explicación del código
[/resumen]

 

[titulo]Nuestro código[/titulo]

El código PHP que lo hace posible va situado en el archivo header.php de nuestro tema, y es el siguiente:

<div class="cart-box">
                                <ul class="d-flex justify-content-sm-between  align-items-center">
				<?php global $woocommerce; ?>
                                   <li class="desplega_carrito" style="min-width: 180px;"><a href="https://elperezoso.es/carrito/"><img src="https://elperezoso.es/wp-content/uploads/2018/10/icon_cart.png" alt="cart-icon"><span class="total-pro"><?php echo sprintf ( _n( '%d item', '%d items', WC()->cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?></span><span class="my-cart"><span>Mis<br>Compras</span></span></a>
                                          
										<ul class="ht-dropdown cart-box-width flyout">
                                            <li>
                                                <?php 
												//lista del producto del carrito
												$items = $woocommerce->cart->get_cart();
												foreach($items as $item => $values) { 
												$productDetail = wc_get_product( $values['product_id'] ); 
												?>
												<!-- Cart Box Start -->
												
                                              <div class="single-cart-box">
                                                    <div class="cart-img">
                                                        <a href="#"><?php echo $productDetail->get_image(); ?></a>
                                                        <span class="pro-quantity"><?php echo $values['quantity'] ?></span>
                                                    </div>
                                                    <div class="cart-content">
                                                        <h6><a href="product.html"><?php echo $productDetail->get_title(); ?></a></h6>
                                                        <span class="cart-price"><?php echo get_post_meta($values['product_id'] , '_price', true); ?>€</span>
                                                    </div>
                                                    <a class="del-icone" href="<?php echo WC()->cart->get_remove_url( $item ); ?>"><i class="ion-close"></i></a>
                                                </div>
                                               <?php } ?>
                                               
                                                <!-- Cart Box End -->
                                                <!-- Cart Footer Inner Start -->
                                                <div class="cart-footer">
                                                   <ul class="price-content">
                                                       <li>Total <span><?php echo WC()->cart->get_cart_total(); ?></span></li>
                                                   </ul>
                                                    <div class="cart-actions text-center">
                                                        <a class="cart-checkout" href="https://elperezoso.es/carrito/">Finalizar Compra</a>
                                                    </div>
                                                </div>
                                                <!-- Cart Footer Inner End -->
                                            </li>
                                        </ul>
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <!-- Cart Box End Here -->
                    </div>

 

A continuación pasamos a explicar las partes más importantes de la programación.

 

[titulo]Explicación del código[/titulo]

En primer lugar hay que decirle a nuestra instalación de WordPress que vamos a comenzar a utilizar funciones de WoCommerce. Para ello realizamos la llamada:

<?php global $woocommerce; ?>

 

La función [codigo]get_cart_contents_count()[/codigo] nos ayudará a extraer la suma del [subraya_verde]número de items[/subraya_verde] que hay ahora mismo en el carrito.

Por lo tanto:

<?php echo sprintf ( _n( '%d item', '%d items', WC()->cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?>

Imprimirá el número allá donde lo situemos.

 

Para [subraya_verde]extraer los productos del carrito[/subraya_verde] junto a sus precios, títulos, fotografías… debemos realizar un [codigo]foreach[/codigo] a la función [codigo]get_cart()[/codigo]:

$items = $woocommerce->cart->get_cart();
foreach($items as $item => $values) { 
}

 

Las siguientes funciones:

[codigo]get_image()[/codigo]: Extrae el thumnail del producto

[codigo]get_title()[/codigo]: Extrae el título del producto

[codigo]get_remove_url()[/codigo]: Crea el enlace que borrará el producto

[codigo]get_cart_total()[/codigo]: Nos aporta el sumatorio total de todos los precios de los productos del carrito

[codigo]get_post_meta()[/codigo]: Extrae detalles del producto tales como precio, número de unidades de ese producto, etc

Para utlilizar [codigo]get_post_meta()[/codigo] dentro del loop habrá que hacer lo siguiente:

//Extrae el precio del producto cuya id hemos facilitado
<?php echo get_post_meta($values['product_id'] , '_price', true); ?>

 

¿Te ha parecido útil esta entrada? ¿Has conseguido crear tu propio carrito? ¿Te has atascado en algún punto y necesitas ayuda? ¡No dudes en darnos tu opinión en los comentarios y compartir esta entrada!

Cristian Sarabia Martínez

Desde que a principios de los 90 mi padre desempolvó su Spectrum, no he dejado de probar y experimentar con la tecnología.

Enamorado del mundo web, Full Stack Developer de profesión y diseñador por devoción.

Ahora hago mis pinitos en esto del blogging para compartir con vosotros un poquito de todo lo que la comunidad me ha dado.

4 Comentarios

Haz clic aquí para dejar tu comentario

Responder a David Ballestero Cancelar Respuesta

Flickr

  • Anja
  • Reader
  • très près
  • brève
  • dans un filet
  • Catriona
  • bad weather
  • gun  & shadow
  • Bidule

About Author

ThemeForest

Collaboratively harness market-driven processes whereas resource-leveling internal or "organic" sources. Competently formulate.

Calendar

septiembre 2025
L M X J V S D
1234567
891011121314
15161718192021
22232425262728
2930  

RSS Meks Blog

  • How Adding Slack Bot Boosted Our Culture of Appreciation 3 julio, 2024
    Sweet Kudos is a Slack bot that enhances employee recognition, rewards, and celebrations within your team. It empowers team members to express gratitude and appreciation effortlessly by giving virtual Kudos. The post How Adding Slack Bot Boosted Our Culture of Appreciation appeared first on Meks.
    Dusan Milovanovic
  • 10 Best Knowledge Base & Wiki WordPress Themes 2021 15 septiembre, 2021
    Running a successful online business requires an exceptional WordPress knowledge base theme that organizes documentation and helps customers. Customization options, intuitive navigation, unique layouts, and fast responsiveness are just some of the features you need. The following 10 WordPress wiki themes represent the best options for 2021 and beyond. Explore the full range to determine […]
    Dusan Milovanovic
  • How to increase WordPress Memory Limit (quick fixes) 16 junio, 2021
    Here is a post about how to increase the memory limit in WordPress. Allowed memory size exhausted error message showed up in your WordPress installation? No worries – this is one of the most common errors in WordPress. You can apply an easy fix by increasing the memory limit in your PHP. Table of Contents […]
    Dusan Milovanovic
  • How to use (and why) WordPress sitemap plugin 1 marzo, 2021
    Did you know that by knowing how to use the WordPress sitemap plugin you can significantly improve your site’s visibility and traffic? Although it isn’t mandatory to have a sitemap on your site, having one significantly improves the site’s quality, crawlability and indexing. All this is important for better optimization, which is why we wanted […]
    Ivana Cirkovic
  • 22 free and premium podcast software for your show [2021 edition] 18 enero, 2021
    You’re determined to start or improve your podcast but don’t know which podcast software to use to really make it stand out? We’ve got you! #podcasting Top 22 free and premium podcast software for your show #WordPressTips #podcasting The post 22 free and premium podcast software for your show [2021 edition] appeared first on Meks.
    Ivana Cirkovic
  • Digital storytelling with WordPress – an all-in-one guide to make your web stories pop! 23 noviembre, 2020
    Wondering how to improve digital storytelling with WordPress and build more awareness and exposure of your business? Let our guide lead the way. The post Digital storytelling with WordPress – an all-in-one guide to make your web stories pop! appeared first on Meks.
    Ivana Cirkovic
  • How to use WordPress autoposting plugin to improve your visibility and SEO? 10 septiembre, 2020
    Did you know you can use the WordPress autoposting plugin for your content efforts and improve not only your time management but your business and visibility as well? The post How to use WordPress autoposting plugin to improve your visibility and SEO? appeared first on Meks.
    Ivana Cirkovic
  • How to create a personal branding site? Step-by-step DIY guide 15 agosto, 2020
    Looking for ways and means to create a personal branding site? Well, look no further ’cause we’re giving away all the how-to’s to do it yourselves! The post How to create a personal branding site? Step-by-step DIY guide appeared first on Meks.
    Ivana Cirkovic
  • Top 15 WordPress content plugins and tools to improve your visibility and rankings 16 julio, 2020
    Let’s take a look at some of the must-have WordPress content plugins and tools to use to improve both your UX and rankings. The post Top 15 WordPress content plugins and tools to improve your visibility and rankings appeared first on Meks.
    Ivana Cirkovic
  • WCEU 2020 recap – key takeaways from the biggest online WordPress conference 9 junio, 2020
    Missed WCEU 2020 and all the exciting stuff from there? Here are all the key takeaways and main points to remember so, take notes! The post WCEU 2020 recap – key takeaways from the biggest online WordPress conference appeared first on Meks.
    Ivana Cirkovic

Text

Distinctively utilize long-term high-impact total linkage whereas high-payoff experiences. Appropriately communicate 24/365.

Archives