How to get next previous category in same taxonomy?

Is there any WP built in function which does the right job?

No.

[Do I] have to write a custom query for that?

No. Use get_terms(). Here is an example.


Add the wpse_99513_adjacent_category class to the functions.php theme file and call it like this:

$category_ids = new wpse_99513_adjacent_category( 'category', 'id', false );

— ‘category’ is the taxonomy,
— ‘id’ is the field to order the database query by and
— false shows empty categories.

To get the next taxonomy use this:

$next_category = $category_ids->next( $category );

— $category is the id of the category you are checking,
— $next_category is set to false if there is an error and the next ID otherwise.

Previous works the same way:

$previous_category = $category_ids->previous( $category );

— $category is the id of the category you are checking,
— $previous_category is set to false if there is an error and the previous ID otherwise.

For slugs which skips empty categories use:

$category_ids = new wpse_99513_adjacent_category( 'category', 'slug' );

class wpse_99513_adjacent_category {

    public $sorted_taxonomies;

    /**
     * @param string Taxonomy name. Defaults to 'category'.
     * @param string Sort key. Defaults to 'id'.
     * @param boolean Whether to show empty (no posts) taxonomies.
     */
    public function __construct( $taxonomy = 'category', $order_by = 'id', $skip_empty = true ) {

        $this->sorted_taxonomies = get_terms(
            $taxonomy,
            array(
                'get'          => $skip_empty ? '' : 'all',
                'fields'       => 'ids',
                'hierarchical' => false,
                'order'        => 'ASC',
                'orderby'      => $order_by,
            )
        );
    }

    /**
     * @param int Taxonomy ID.
     * @return int|bool Next taxonomy ID or false if this ID is last one. False if this ID is not in the list.
     */
    public function next( $taxonomy_id ) {

        $current_index = array_search( $taxonomy_id, $this->sorted_taxonomies );

        if ( false !== $current_index && isset( $this->sorted_taxonomies[ $current_index + 1 ] ) )
            return $this->sorted_taxonomies[ $current_index + 1 ];

        return false;
    }

    /**
     * @param int Taxonomy ID.
     * @return int|bool Previous taxonomy ID or false if this ID is last one. False if this ID is not in the list.
     */
    public function previous( $taxonomy_id ) {

        $current_index = array_search( $taxonomy_id, $this->sorted_taxonomies );

        if ( false !== $current_index && isset( $this->sorted_taxonomies[ $current_index - 1 ] ) )
            return $this->sorted_taxonomies[ $current_index - 1 ];

        return false;
    }
}

Leave a Comment