How to automatically redirect external or affiliate products in WooCommerce by clicking on the photo or title directly to your link [RESOLVED]

If you have an affiliate store made with WooCommerce, you may be interested in redirec your users when they click on a product, and there that it takes them directly to its external link. On one hand you avoid having to create content for each product (and bring SEO to the level of categories, for example) and on the other hand you increase conversions.

Improving the web of CursosBaratos.Online in 2019 this need arose for us, and it took us some time to find a solution that worked with the latest versions of WooCommerce, since there are several alternatives on the Internet but they are obsolete. It was finally thanks to adapting some of the information we found in Stack Overflow that we could make it run … and the result is spectacular.

What needs to be done?

What I am going to teach you in this post is precisely to solve this problem. For this you should simply add some code to the functions.php file of your theme. It is very important that you create a “child theme” to do this, if you don’t do that, these changes could be lost when updating the theme. The code is this:

add_action( 'template_redirect', 'redirect_external_products' );
function redirect_external_products() {
    global $post;
    if ( is_singular( 'product' ) && ! empty( $post ) && ( $product = wc_get_product( $post ) ) && $product->is_type( 'external' ) ) {
        wp_redirect( $product->get_product_url() ); 
        exit;
    }
}

function custom_woocommerce_template_loop_product_link_open() {
    echo '<a href="' . get_the_permalink() . '" rel="nofollow">';
}

With this it should work. Hope this can help you. If you have any questions or improvements about this code, you can leave it in the comments. See you soon!