This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.
Working with WordPress hooks can be quite exciting, especially when you want to customize your website in unique ways. One such hook is the get_adjacent_post_sort filter, which can be quite handy when you need to manage post adjacency. Let’s dive into how you can make the most out of this hook.
Understanding get_adjacent_post_sort
The dynamic portion of the hook name, $adjacent, refers to the type of adjacency, ‘next’ or ‘previous’. To use the get_adjacent_post_sort filter, first, you have to register it using add_filter. You can write this code into functions.php of your activated theme or in a custom WordPress Plugin. At WePlugins, we always prefer to create a custom WordPress Plugin while using hooks so nothing breaks when you update your WordPress Theme in the future.
Parameters
Below are the 3 parameters required to use this hook.
- $order_by: (string) The ORDER BY clause in the SQL.
- $post: (WP_Post) WP_Post object.
- $order: (string) Sort order. ‘DESC’ for previous post, ‘ASC’ for next.
Example 1: Basic Usage of get_adjacent_post_sort
Below is an example of how you can use this hook to modify post sorting.
function weplugins_modify_get_adjacent_post_sort_defaults($order_by, $post, $order) { // Update the $order_by variable according to your website requirements and return this variable. return $order_by; } // Add the filter add_filter("get_adjacent_post_sort", "weplugins_modify_get_adjacent_post_sort_defaults", 10, 3);
Example 2: Removing a Hook Callback
To remove a hook callback, use the example below.
remove_filter("get_adjacent_post_sort", "weplugins_modify_get_adjacent_post_sort_defaults", 10, 3);
Please make sure to provide the same callback function name, priority, and number of arguments while removing the hook callback.
Example 3: Conditional Order Update
Sometimes, you may want to update the order conditionally. Here’s how you can do it.
function weplugins_conditional_modify_get_adjacent_post_sort($order_by, $post, $order) { if ($order === 'DESC') { $order_by = 'post_date DESC'; } else { $order_by = 'post_date ASC'; } return $order_by; } add_filter("get_adjacent_post_sort", "weplugins_conditional_modify_get_adjacent_post_sort", 10, 3);
Contact Us
If you’re having any trouble using this hook or need customization, please contact us and we’d be happy to assist you.
Explore the latest in WordPress
Trying to stay on top of it all? Get the best tools, resources and inspiration sent to your inbox every Wednesday.