CMS Woocommerce WordPress

[WordPress][WooCommerce] Redireccionar página al finalizar pedido según el producto que se compre

[titulo]Obtener el id de productos adquiridos al finalizar compra[/titulo] [subraya_rosa]Un cliente que ya ha realizado una compra es el mejor activo que podemos tener:[/subraya_rosa] Le ha interesado nuestro producto, ha cedido sus datos y ha generado un perfil de gustos.

Ahora solo queda no fallarle y, como mínimo, cumplir sus espectativas.

Una estrategia de marketing muy buena y poco utilizada, es [subraya_verde]aprovechar la Thank You Page de Finalizar Compra para realizar remarketing.[/subraya_verde] A esta página se accede tras realizar el pago, y normalmente WooCommerce la utiliza para mostrar un resumen de compra.

¿Por qué no darle una vuelta de tuerca y mostrar productos o promociones relacionadas que le inciten a volver pronto? Esta estrategia, muy utilizada en webs como JustEat o Booking, da resultados muy buenos, pero para ser realmente efectiva tenemos que saber qué mostrar de toda nuestra tienda.

Si el cliente ha adquirido unas zapatillas deportivas, tal vez podríamos mostrarle calcetines y camisetas técnicas, relojes deportivos, cronómetros…

¿Y cómo lo hacemos?

 

[titulo]El código paso a paso[/titulo]

Tenemos que indicar a WooCommerce que el código se ejecutará justo tras la compra. Para ello nos aprovechamos de la url que devolverá el plugin y buscamos que contenga [codigo]order-received[/codigo]:

if ( ! is_wc_endpoint_url( 'order-received' ) ) return;

Después conectamos con las funciones de WordPress para poder hacer uso de su flujo de datos:

global $wp;

El siguiente paso es extraer el ID de la orden, que también lo podemos extraer de la url.

Si el slug está en español:

$order_id =  intval( str_replace( 'finalizar-compra/order-received/', '', $wp->request ) );

Si el slug esta en inglés:

$order_id =  intval( str_replace( 'checkout/order-received/', '', $wp->request ) );

Y ahora podemos extraer los productos que se adquirieron en esa orden de compra:

$order = wc_get_order( $order_id );
$items = $order->get_items();

Recorremos el array:

 foreach ( $items as $item ) {
        $product_id = $item->get_product_id(); //Para el id de producto
        $product_name = $item->get_name(); //Para el nombre de producto
        $product_variation_id = $item->get_variation_id(); //Para la variación si es un producto variable
}

En nuestro caso particular emplearemos únicamente el [codigo]product_id[/codigo]. Y realizaremos un redireccionamiento en cuanto encontremos que se ha adquirido algún producto de los que vamos a usar en nuestro remarketing.

Así que en lugar de lo anterior, nosotros haremos:

 foreach ( $items as $item ) {
        $product_id = $item->get_product_id();

        if ($product_id == 2700){
            wp_redirect( home_url( '/pediatra-online-consulta-interactiva/' ) );
            break;
        }

        if ($product_id == 2564){
            wp_redirect( home_url( '/pediatra-online-enviar-email/' ) );
            break;
        } 
    }

 

¡Ya ya está! Solo queda envolverlo todo en una función, añadirle en enque y subirlo al archivo [codigo]functions.php[/codigo] de nuestro tema activo o del child theme.

 

[titulo]El código completo[/titulo]

Para que os resulte más fácil, os lo ponemos completo:

add_action( 'template_redirect', 'wc_custom_redirect_after_purchase' );
function wc_custom_redirect_after_purchase() {
    if ( ! is_wc_endpoint_url( 'order-received' ) ) return;


    global $wp;
    
    $order_id =  intval( str_replace( 'finalizar-compra/order-received/', '', $wp->request ) ); // ID de la orden
    $order = wc_get_order( $order_id ); 

    $items = $order->get_items();

    foreach ( $items as $item ) {
        $product_id = $item->get_product_id();

        if ($product_id == 2700){
            wp_redirect( home_url( '/pediatra-online-consulta-interactiva/' ) );
            break;
        }

        if ($product_id == 2564){
            wp_redirect( home_url( '/pediatra-online-enviar-email/' ) );
            break;
        } 
    }
   
}

 

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.

1 Comentario

Haz clic aquí para dejar tu comentario

  • Gracias por tu post me ha sido de mucha ayuda sali de ciertas dudas, ahora si yo quisiera mostrar el checkout y luego de unos segundos redirigir a una pagina de agradecimiento personalizada?

Flickr

  • Helicomore
  • Yorkstr.
  • Eyes
  • Concierge
  • Vajras en valdrague
  • J.
  • Walk
  • Querschnitt
  • Sunbath

About Author

ThemeForest

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

Calendar

julio 2024
L M X J V S D
1234567
891011121314
15161718192021
22232425262728
293031  

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