Skip to content
Read For Learn
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP
Read For Learn
  • Database
    • Oracle
    • SQL
  • C
  • C++
  • Java
  • Java Script
  • jQuery
  • PHP

Next/Previous Product with custom order by price & products inside the product category [closed]

I managed to modify an existing answer from a closely related thread to achieve this.
You can find the answer from the related thread here.
https://wordpress.stackexchange.com/a/365334/185141

add_action('woocommerce_before_single_product', 'elron_prev_next_product');

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

function elron_prev_next_product() {
    
   global $post;
    
   echo '<div class="prev-next-buttons">';
   $terms = get_the_terms( $product->id, 'product_cat' );  
   foreach ($terms as $term) {
   if ($term->ID == $category->cat_ID) {
   $all_posts = new WP_Query(
      array(
         'post_type' => 'product',
         'meta_key' => '_price', // <-- CHANGE THIS
         'orderby' => 'meta_value',
         'order' => 'ASC',
         'post_status' => 'publish',
         'posts_per_page' => -1,
         'tax_query' => array(
                array(
                        'taxonomy' => 'product_cat',
                        'field'      => 'term_id',
                        'terms'    => $terms[0]->term_id
                     )
         )
      )
   );
       break;
   }
   }
   foreach ($all_posts->posts as $key => $value) {
      if ($value->ID == $post->ID) {
         $nextID = $all_posts->posts[$key + 1]->ID;
         $prevID = $all_posts->posts[$key - 1]->ID;
         break;
         wp_reset_postdata();
      }
   }

   if ($prevID) : ?>
      <a href="<?= get_the_permalink($prevID) ?>" rel="prev" class="prev" title="<?= get_the_title($prevID) ?>"><?= esc_attr__('Previous product') ?></a>
   <?php endif; ?>
   <?php if ($nextID) : ?>
      <a href="<?= get_the_permalink($nextID) ?>" rel="next" class="next" title="<?= get_the_title($nextID) ?>"><?= esc_attr__('Next product') ?></a>
   <?php endif; ?>
   <?php

   echo '</div>';
}

I know i was searching for a way to make next/prev button on my product pages that were sorted by price and gave products only inside the product category i was on, for a long time, if you did as well give an upvote! 🙂

EDIT: You can also limit the query created to output products that aren’t outofstock

$all_posts = new WP_Query(
      array(
         'post_type' => 'product',
         'meta_key' => '_price', // <-- CHANGE THIS
         'orderby' => 'meta_value',
         'order' => 'ASC',
         'post_status' => 'publish',
         'posts_per_page' => -1,
         'meta_query' => array(
            array(
                'key' => '_stock_status',
                'value' => 'outofstock',
                'compare' => '!=',
            )
         ),      
         'tax_query' => array(
                array(
                        'taxonomy' => 'product_cat',
                        'field'      => 'term_id',
                        'terms'    => $terms[0]->term_id
                     )
         )
      )
   );

EDIT 2: Although the above code works just fine in all my tests, there are 2 notices generated from wp_debug

Notice: Undefined variable: product in /public/wp-content/themes/generatepress_child/functions.php on line 2098

Notice: Trying to get property 'id' of non-object in /public/wp-content/themes/generatepress_child/functions.php on line 2098

Notice: Undefined variable: category in /public/wp-content/themes/generatepress_child/functions.php on line 2100

Notice: Trying to get property 'cat_ID' of non-object in /public/wp-content/themes/generatepress_child/functions.php on line 2100

2098 line: $terms = get_the_terms( $product->id, 'product_cat' );
2100 line: if ($term->ID == $category->cat_ID) {

Related Posts:

  1. Can the Next/Prev Post links be ordered by menu order or by a meta key?
  2. WooCommerce conditional meta query
  3. WooCommerce product sorting VERY slow
  4. WooCommerce: Adding Order Item Meta Data That’s Hidden
  5. Sort orders by custom order meta – Woocommerce Orders admin page
  6. WP_Query with meta_query for children
  7. How to update custom field in WooCommerce
  8. How to upload multiple image using wp_insert_post
  9. Set default value field meta_Value [closed]
  10. Sort & Display WooCommerce Product Attributes by Order
  11. update_post_meta not work [closed]
  12. Woocommerce – Problem sorting and filtering products with different tax rates by price [closed]
  13. WooCommerce order refund get qty refunded
  14. Order woocommerce products alphabetically by second word in title?
  15. WooCommerce Bookings Plugin Not Saving Order ID
  16. Conditionally run function based on custom meta value?
  17. How to add custom checkboxes from loop to WooCommerce product variation options?
  18. Sort products by Sale price and stock status
  19. How to sort products by price ASC and place all no price products to the end? (Woocommerce)
  20. How to exclude posts by meta key value in the_post_navigation next prev links?
  21. How to save a Woocomerce metabox input as a metadata field
  22. Can’t update WooCommerce payment method title
  23. Multiple sorting criteries (order by)
  24. Update Custom Post Meta Even if Draft
  25. How to programatically create a WooCommerce downloadable product?
  26. Sort by promo code used woocommerce admin panel [closed]
  27. Updating order meta to have a meta entry from an item in the order
  28. acf_form() – “On Update” action [closed]
  29. Woocommerce backend sorting product drag drop by menu_order to date
  30. Sort by price when price is set in multiple keys
  31. woocommerce pagination. not working when sorting used
  32. Add multiple products to woocommerce cart
  33. woocomerce products and categories don’t display fixed
  34. How to make product free for some customers and paid for others?
  35. Advanced Custom Fields missing Woocomerce in Rules
  36. Duplicate post/product permalinks. (Link is temporary)
  37. Add an extra column to /my-account/subscriptions/ WooCommerce page
  38. woocommerce: when adding or removing items to cart , it takes cart a few seconds to read changes?
  39. How to add a fixed shopping cart button on the bottom of the page?
  40. WooCommerce – different icons for product categories
  41. WordPress returning “XHR” even when access keys are used
  42. mydomain.com/wp-login redirects to wordpress.com/wp-login
  43. Woocommerce Languages Files
  44. Previous/Next custom post links within custom taxonomy
  45. How to get woocommerce integration instance?
  46. Understanding WooCommerce Build-In Geolocation/ Geo_IP classes
  47. WooCommerce Admin Only Email Hook
  48. Woocommerce – Dynamic Link to The Most Recently Added Product
  49. How to adjust Related Page Thumb Sizes on single page?
  50. Create woocommerce order on new user registration
  51. Adding more than one item to Woocommerce cart
  52. How to put a date range in a virtual/downloadable product? [closed]
  53. How to know if the most recent article
  54. How to filter get previous post function by meta value DESC and post date DESC?
  55. How to set up a single product shop with woocommerce? Skipping the product archive
  56. I’m trying to display product categories on each product in the list
  57. previous and next post of same category on singlepost.php
  58. Update products, terms and relations via SQL
  59. Cross-sells on WooCommerce product page
  60. Woocommerce Child Category Permalink Structure Change
  61. How to allow registration only from a certain location?
  62. Add confirmation popup on place order button
  63. Allow customer to choose an optional free/paid product to add to their order (and reduce stock reduced & record sale)
  64. Admin Order adding an extra product on add_line_item
  65. How to get the WooCommercer product variation image
  66. how add css class to product boxes li, for img, add cart button, decs, price… [closed]
  67. How to restrict type/size of file uploads in any plugin?
  68. How do I modify the Previous and Next Page posts on blog pages to include “previous” and “next” before the links?
  69. In woocommerce some products have empty options, but how to check this
  70. Get Third Level Categories WooCommerce
  71. Not all strings are translated
  72. Site doesn’t work when updating to SSL using nginx
  73. Custom Woocommerce checkout filed yields a Json error when validating [closed]
  74. Change wp-login.php? Problem with .htaccess password protection and multi user shop
  75. Conditional email recipient based off Shipping Method [closed]
  76. access Woo commerce | WordPress methods externally
  77. woocommerce displaying products of a specific page
  78. Woocommerce: Some action hooks not firing inside class [closed]
  79. Save Woocomerce discount as percentage to database
  80. Custom excerpt length WooCommerce product
  81. How Do I Access Parameters Emitted by an Action?
  82. How to store ACF from product in user_meta?
  83. Woocommerce Shipping based on condition and cart value
  84. How to display woocommerce products of one wordpress account in another wordpress account?
  85. When to use a child theme for WooCommerce Storefront?
  86. Woocommerce Custom Rewrite Rules Array – Subcategories
  87. Changing second user role while updating/downgrading membership level – s2member [closed]
  88. Clone and modify Woocommerce Products catalog
  89. How to Navigate within Category? Lot of codes here on stackexchange didn’t work
  90. Same WooComerce shop for different WP sites?
  91. I need to customize wordpress “previous” “next” links
  92. How to Display Amount of products being displayed out of the amount in category – WordPress/Woocommerce
  93. Custom Shipping Method: need non-instance settings and non-global settings
  94. Woocommerce – get product in category with specific attribute
  95. Woocommerce update cart
  96. Stop the “upload file size” error from printing [closed]
  97. Woocommerce make appear when items added to cart
  98. Getting one specific value from get_children array
  99. Get WP All Export row ID
  100. Is it possible Different templates of products for specific category in WooCommerce?
Categories woocommerce-offtopic Tags next-post-link, post-meta, previous-post-link, sort, woocommerce-offtopic
enqueuing external and internal js and css in wordpress did not work with owl.js animate.css
Archive product loop does not work with product filters

Recommended Hostings

Cloudways: Realize Your Website's Potential With Flexible & Affordable Hosting. 24/7/365 Support, Managed Security, Automated Backups, and 24/7 Real-time Monitoring.

FastComet: Fast SSD Hosting, Free Migration, Hack-Free Security, 24/7 Super Fast Support, 45 Day Money Back Guarantee.

Recent Added Topics

  • Bug in translation system: load_theme_textdomain() returns true, files are available and accessible but the language defaults to english
  • Post Navigation Elementor
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • WPFacet multiple loop displaying duplicate content
  • Get the name of the template/*html file used
  • Fix: WordPress.DB.PreparedSQL.NotPrepared Plugin Check (PCP)
  • Removing unnecessary CSS and JS code from wp_head()
  • hexagonal image gallery. Am I on the right track? [closed]
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
© 2026 Read For Learn
  • Database
    • Oracle
    • SQL
  • algorithm
  • asp.net
  • assembly
  • binary
  • c#
  • Git
  • hex
  • HTML
  • iOS
  • language angnostic
  • math
  • matlab
  • Tips & Trick
  • Tools
  • windows
  • C
  • C++
  • Java
  • javascript
  • Python
  • R
  • Java Script
  • jQuery
  • PHP
  • WordPress