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. remove default pagination on woocommerce shop page
  32. WordPress Comment Box on woocommerce product page [closed]
  33. Remove Bulk Action For non admin user
  34. Add max-value to hooked quantity selector in woocommerce [closed]
  35. Can’t remove woocommerce sidebar
  36. Woocommerce Slow Queries
  37. woo product , wp_insert_post() never displays on the front end. What gives? [closed]
  38. Single.php Category Post Count
  39. Disabling shopping basket in WooCommerce [closed]
  40. Single product page doesn’t display price
  41. Should I use docker in wordpress production?
  42. can’t get the product id in single woocommerce page
  43. Php echo woocommerce price
  44. Different files for order details
  45. Multiple Schema.org markups on a single product page
  46. Woocommerce – Adding row to cart table
  47. Hide a product with a certain tag from product-category
  48. Custom rewrite for product variation not working
  49. WordPress post next/prev not working
  50. WooCommerce get_author_posts_url() – Author URL redirecting to shop base
  51. Error message if user is buying less than 200 euros of a given product [closed]
  52. WooCommerce show a variation both in check boxes and in a list
  53. Woocommerce – How to mix products and posts on a landing page?
  54. Disable woocommerce product search plugin’s autocomplete [closed]
  55. Sort taxonomy page alphabetically by meta rather than default post date
  56. How to get next post link of child custom post type from parent post and get next post link of parent post from the last child post?
  57. How to integrate e-transfers with checkout in WooCommerce
  58. Manual Admin Orders search for billing_company
  59. Use woocmmerce function on theme and override them
  60. Send all emails to Shop Manager along with admin
  61. Snippet to copy product affiliate link to a custom field
  62. Woocommerce Checkout Page Total Price Inside Google Pay Script
  63. How to hide order action button after changing order status to completed
  64. How to get rid of variations with unspecified attributes
  65. Deregister dequeue JS scripts except on 1 product page
  66. Change password notification email
  67. How to show price update date in product single page?
  68. Woocommerce Rest API: woocommerce_product_invalid_image_id
  69. how can my customers view their purchased products history like an invoice in a specific page on WordPress
  70. How do I make my products on the homepage responsive?
  71. How to get users data from wordpress woocomerce database to display
  72. Simple thing esc_url query
  73. Woocommerce on Subdirectory
  74. Change WooCommerce state and city checkout fields to dropdowns related to the chosen country
  75. How to apply a custom coupon to a WooCommerce Subscription recurring amount?
  76. Using previous_post_link next_post_link but with a filter on a custom field
  77. WooCommerce: How can I add a certain product to the cart and redirect to the cart from a non-shop page?
  78. Make Woocommerce breadcrumbs show up using functions.php file
  79. Alter the cost of products using phpmyadmin sql query
  80. How does one allow any customer to process any order in store on woocommerce?
  81. Update products with curl (bash)
  82. Create woocommerce order on new user registration
  83. How to put a date range in a virtual/downloadable product? [closed]
  84. Woocommerce Child Category Permalink Structure Change
  85. Allow customer to choose an optional free/paid product to add to their order (and reduce stock reduced & record sale)
  86. How to restrict type/size of file uploads in any plugin?
  87. Stop the “upload file size” error from printing [closed]
  88. Redirect whole website or pages to /wp-admin in wordpress
  89. Changing sale price programmatically, but it’s not shown on front-end
  90. How to disable the “Upgrade or Downgrade” button in “My account” of WooCommerce Subscriptions
  91. WooCommerce – Inconsistent Indexing of Orders
  92. Retrieving next_post_link() and previous_post_link() in functions.php
  93. How to remove slug from Product category URL in Woocommerce
  94. Removing ‘woocommerce-no-js’ class from body
  95. url rewrite doesn’t load woocommerce product
  96. Critical error on woocommerce checkout page
  97. Can’t add variable products since update WooCommerce [closed]
  98. Add custom ID to WooCommerce product tab
  99. Optimizing or rewriting core queries
  100. WooCommerce admin>edit-comments show none [closed]
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
  • Custom Elementor controls not appearing in the widget Advanced tab using injection hooks
  • Get the name of the template/*html file used
  • Trying to Add Paging to Single Post Page
  • Sharing media files between live and staging servers
  • How to display the description of a custom post type in the dashboard?
  • Critical error on image display
  • Copying WP data and files into new install?
  • How to determine the DirectAdmin WordPress backup date?
  • How to get list of ALL tables in the database?
© 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