WordPress.org

Ready to get started?Download WordPress

Forums

Category link in post to page location (2 posts)

  1. RogerUsh
    Member
    Posted 1 year ago #

    Is it possible to link to the exact page that the post is on in the categories archive?

    For example, if a post is in the category "drawings", when I click on the the_category() link in single.php it will bring me to "url.com/drawings/page/3"

    Thanks.

  2. keesiemeijer
    moderator
    Posted 1 year ago #

    Try it with this in your theme's functions.php:

    function add_pagenumber_to_cat_link( $termlink, $term_id ) {
    
    	global $post, $wpdb;
    
    	if( !$post )
    		return $termlink;
    
    	$where = get_posts_by_author_sql( $post->post_type );
    
    	$query = "SELECT count(*) FROM $wpdb->posts  INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) $where AND ($wpdb->term_relationships.term_taxonomy_id IN ($term_id) ) AND $wpdb->posts.post_date >= '$post->post_date' ORDER BY $wpdb->posts.post_date DESC";
    
    	$count  = (int) $wpdb->get_var( $query );
    
    	if($count) {
    		$posts_per_page = get_option( 'posts_per_page' );
    		$cat_num_page = ceil( $count / $posts_per_page );
    
    		if($cat_num_page > 1) {
    			$termlink = add_query_arg( 'paged', $cat_num_page, $termlink );
    		}
    	}
    
    	return $termlink;
    }

    in single.php use the_category() like this:

    <?php
    add_filter( 'category_link', 'add_pagenumber_to_cat_link',10,2 );
    the_category();
    remove_filter( 'category_link', 'add_pagenumber_to_cat_link',10,2 );
    ?>

Topic Closed

This topic has been closed to new replies.

About this Topic