Home » WooCommerce: Add Next/Previous @ Single Product Page

WooCommerce: Add Next/Previous @ Single Product Page

by Tutor Aspire

A very nice client 🙂 had a very nice challenge the other day, so I thought of “donating” this valuable snippet to all of you!

After researching the internet high and low and not finding anything simple that also worked (in particular this snippet on StackOverflow and this Gist on Github), I decided to DIY!

Here’s what I came up with – enjoy!

WooCommerce: Add Next/Previous Links to Single Product Page
WooCommerce: Add Next/Previous Links to Single Product Page

PHP Snippet (Part 1 of 3): Display Next/Previous Product Buttons (from the same Category) @ Single Product Page

/**
 * @snippet       Add next/prev buttons @ WooCommerce Single Product Page
 * @how-to        Get tutoraspire.com FREE
 * @sourcecode    https://tutoraspire.com/?p=20567
 * @author        Tutor Aspire
 * @testedwith    WooCommerce 2.5.5
 */

add_action( 'woocommerce_before_single_product', 'tutoraspire_prev_next_product' );

// and if you also want them at the bottom...
add_action( 'woocommerce_after_single_product', 'tutoraspire_prev_next_product' );

function tutoraspire_prev_next_product(){

echo '
'; // 'product_cat' will make sure to return next/prev from current category $previous = next_post_link('%link', '← PREVIOUS', TRUE, ' ', 'product_cat'); $next = previous_post_link('%link', 'NEXT →', TRUE, ' ', 'product_cat'); echo $previous; echo $next; echo '
'; }

CSS (Part 2 of 3): Style Next/Previous Buttons @ Single Product Page

Just because I’m nice I decided to give you some cool styling as well. In particular, we make sure the buttons float one to the left and one to the right and that the whole new row displays as block.

/* CSS */

.prev_next_buttons {
line-height: 40px;
margin-bottom: 20px;
}

.prev_next_buttons a[rel="prev"], .prev_next_buttons a[rel="next"] {
display: block;
}

.prev_next_buttons a[rel="prev"] {
float: right;
}

.prev_next_buttons a[rel="next"] {
float: left;
}

.prev_next_buttons::after {
content: '';
display: block;
clear:both;
}

Product Sorting (Part 3 of 3)

Functions used in the PHP above will work in chronological order, as per “next_post_link” and “previous_post_link” documentation.

Problem is – what if you have WooCommerce products sorted by alphabetical or custom order?

At the end, client found out the best way to make the two work together is by using the free Post Type Order plugin. Simply download it, activate it and sort your products with that plugin – and Next/Previous will now follow this custom sorting.

You may also like