• Resolved igogra

    (@igogra)


    Hi,

    I’m using a custom post type (‘products’) to hold products, each product holds a name via a custom field (‘name_product’). So in the products page (‘page-products.php’) all products are displayed ordered by product name. And when I display the product via its singular template (‘single-products.php’) it would be nice to have a next & previous link to go through those products, but it should go through them in order of their name. Currently that’s not possible as they would be ordered by their publishing dates. How can I manage that?

    This is what I have in page-products.php:

    <?php
    $args = array(
    	'post_type' => 'products',
    	'orderby' => 'meta_value',
    	'meta_key' => 'name_product',
    	'order' => 'ASC'
    );
    
    $products = new WP_Query($args);
    
    if ($products->have_posts()) {
    	while ($products->have_posts()) {
    		 $products->the_post();
    		 ...
    		 // Currently it displays products ordered by name. It works well
    	}
    }
    ?>

    And this is what I have in single-products.php:

    <?php
    if (have_posts()) {
    	while (have_posts()) {
    		the_post();
    		...
    		// Currently it displays the single product but when previous or next post link is clicked the order is by publishing date instead of product name
    		next_post_link('%link', 'Next product');
    		previous_post_link('%link', 'Previous product');
    	}
    ?>

    Thanks.

Viewing 1 replies (of 1 total)
  • Thread Starter igogra

    (@igogra)

    down vote accept

    Finally I solved it!

    I just used the plugin Next/Previous Post Link Plus for WordPress and added the following code in my single page of products (single-products.php):

    <?php next_post_link_plus( array(
                                'order_by' => 'custom',
                                'meta_key' => 'data_product_name_product',
                                'link' => 'Next product',
                                'format' => '%link'
                                )); ?>
    <?php previous_post_link_plus( array(
                                'order_by' => 'custom',
                                'meta_key' => 'data_product_name_product',
                                'link' => 'Previous product',
                                'format' => '%link'
                                )); ?>
Viewing 1 replies (of 1 total)
  • The topic ‘Ordered previous_post_link & next_post_link by custom field’ is closed to new replies.