How to get next previous category in same taxonomy?

Like WP get_adjacent_post function gives the next and previous post data based on the parameters i want to get the next/previous category data is there any WP built in function which does the right job or i have to write a custom query for that.

// Next/previous post example
$in_same_cat = false;
$excluded_categories = '';
$previous = true;
$previous_post = get_adjacent_post($in_same_cat,$excluded_categories,$previous);

i want next category by category slug or by category id

Read More

Any help would be appreciated

Related posts

6 comments

  1. 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;
        }
    }
    
  2. This is what I came up with. Maybe not the best but works 🙂

    Assuming we are on a custom taxonomy category page, and we want to go to the next

    // get the term used on this current taxonomy page
    $term = get_term_by( 'slug', get_query_var('term'), get_query_var('taxonomy') );
    
    //set your arguments
    $args = array(
         'hide_empty' => 0,
         'orderby' => 'name',
         'order' => 'DESC',
    );
    
        //set your vars
    $cycletaxonomy = 'author';
        // get all terms in a custom taxonomy
    
    $cycleterms = get_terms($taxonomy, $args);
    
        // A for loop to cycle through all terms
    for ($x=0; $x<count($cycleterms); $x++){
                // assign current cycled category slug - i could have used id too actually
        $thisslug = $cycleterms[$x]->slug;
    
        if ($curslug == $thisslug) {
            $nextslug = $cycleterms[$x+1]->slug;
            $prevslug = $cycleterms[$x-1]->slug;
            echo $nextslug;
            echo $prevslug;
                        // now do what you want with this slug - like putting it into a link tag
        }
    };
    
  3. I am not sure about bulit-in functions in WordPress but you can

    Get Next and Previous Pages and than their category using next and previous post ID.

  4. This is what i came up with a custom query solution hope it help others i wrote a custom function for this it works for all post type categories (post,custom post types)

    function get_adjacent_category($category_slug,$taxonomy,$type){
        global $wpdb;
        if($type=="next"){
            $operater=" > ";
            $orderby=" ORDER BY tt.`term_id` ASC ";
        }else{
            $operater=" < ";
            $orderby=" ORDER BY tt.`term_id` DESC ";
        }
        $query="SELECT *,(SELECT `term_id` FROM wp_terms WHERE `slug`='".$category_slug."') AS given_term_id,
            (SELECT parent FROM wp_term_taxonomy WHERE `term_id`=given_term_id) AS parent_id
            FROM  `wp_terms` t
            INNER JOIN `wp_term_taxonomy` tt ON (`t`.`term_id` = `tt`.`term_id`)
            HAVING  tt.taxonomy='".$taxonomy."' AND tt.`parent`=parent_id AND tt.`term_id` $operater given_term_id $orderby LIMIT 1";
        return $wpdb->get_row($query);
    }
    
    $next_category =  get_adjacent_category($slug,$taxonomy,"next");
    $previous_category =  get_adjacent_category($slug,$taxonomy,"previous");
    
  5. Little update based on Akmur answer

    $term = get_term_by('slug', get_query_var('term'), get_query_var('taxonomy'));
    $curslug = $term->name;
    $args = array(
        'hide_empty' => 0,
    );
    $cycletaxonomy = 'YOUR_TERM';
    // get all terms in a custom taxonomy
    $cycleterms = get_terms($taxonomy, $args);
    // A for loop to cycle through all terms
    for ($x = 0; $x < count($cycleterms); $x++) {
        // assign current cycled category slug - i could have used id too actually
        $thisslug = $cycleterms[$x]->name;
    
        if ($curslug == $thisslug) {
            $nextslug = $cycleterms[$x + 1]->name;
            $prevslug = $cycleterms[$x - 1]->name;
            echo '<ul class="post-nav">';
            if (!empty($nextslug)) {
                echo '<li class="next"><a href="' . get_term_link(intval($cycleterms[$x + 1]->term_id), 'YOUR_TERM') . '">' . $nextslug . '</a><li>';
            }
            if (!empty($prevslug)) {
                echo '<li class="previous"><a href="' . get_term_link(intval($cycleterms[$x - 1]->term_id), 'YOUR_TERM') . '">' . $prevslug . '</a><li>';
            }
            echo '</ul>';
            // now do what you want with this slug - like putting it into a link tag
        }
    }
    
  6. Place this function in your functions.php:

    function adjacent_post_by_category( $category, $direction, $content ) {
    
        // Info
        $postIDs = array();
        $currentPost = get_the_ID();
    
    
        // Get posts based on category
        $postArray = get_posts( array(
    
            'category' => $category,
            'orderby'=>'post_date',
            'order'=> 'DESC'
    
        ) );
    
    
        // Get post IDs
        foreach ( $postArray as $thepost ):
    
            $postIDs[] = $thepost->ID;
    
        endforeach;
    
    
        // Get prev and next post ID
        $currentIndex = array_search( $currentPost, $postIDs );
        $prevID = $postIDs[ $currentIndex - 1 ];
        $nextID = $postIDs[ $currentIndex + 1 ];
    
    
        // Return information
        if( $direction == 'next' AND $nextID ):
    
            return '<a rel="next" href="' . get_permalink( $nextID ) . '">' . $content . '</a>';
    
        elseif( $direction == 'prev' AND $prevID ):
    
            return '<a rel="prev" href="' . get_permalink( $prevID ) . '">' . $content . '</a>';
    
        else:
    
            return false;
    
        endif;
    
    }
    

    And this as your prev/next links (function parameters are examples):

    <?php echo adjacent_post_by_category( 10, 'prev', 'Show previous post' ); ?>
    
    <?php echo adjacent_post_by_category( 10, 'next', 'Show next post' ); ?>
    

Comments are closed.