WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Pagination in categories with permalink set to postname (3 posts)

  1. manuelmasia
    Member
    Posted 3 years ago #

    Hi, I use this function to paginate posts within categories:

    add_filter( 'pre_get_posts', 'number_of_posts' );
    function number_of_posts( $wp_query = '' ) {
    	remove_filter( 'pre_get_posts', 'number_of_posts' );
    	global $wp_query;
    	$cat_obj = $wp_query->get_queried_object();
    	$category_id = $cat_obj->term_id;
    	if ( is_category(3) ) {
    		$wp_query->query_vars['posts_per_page'] = 2;
    	} elseif( is_category(1)) {
    		$wp_query->query_vars['posts_per_page'] = 1;
    	}
    
    	return $wp_query;
    }

    It works very fine if permalinks are set on default. But, if I use %postname%, it doesn't work, and the number of displayed posts is the same of the global $posts_per_page set in "Settings / Reading"...

    Any idea?

    Thanks in advance!

  2. manuelmasia
    Member
    Posted 3 years ago #

    Ok... I tryed another way:

    add_filter( 'pre_get_posts', 'number_of_posts' );
    function number_of_posts( $wp_query = '' ) {
    	remove_filter( 'pre_get_posts', 'number_of_posts' );
    	global $wp_query;
    	global $wpdb;
    	$cat_obj = $wp_query->get_queried_object();
    
    		if ( $wp_query->is_category ) {
    			if ( !($category_id = $wp_query->get('cat')) ) {
    				$category    = $wp_query->get('category_name');
    				$sqlstr  = "SELECT term_id FROM $wpdb->terms WHERE slug = '". $wpdb->escape($category) ."'";
    				$category_id = (int) $wpdb->get_var($sqlstr);
    				if ( $category_id==3 ) {
    				echo "<script>alert (".$category_id.");</script>";
    					$wp_query->query_vars['posts_per_page'] = 2;
    				} elseif( $category_id==1) {
    				echo "<script>alert (".$category_id.");</script>";
    					$wp_query->query_vars['posts_per_page'] = 1;
    				}
    			}
    			else  {
    				$category_id = $cat_obj->term_id;
    				if ( $category_id==3 ) {
    					$wp_query->query_vars['posts_per_page'] = 2;
    				} elseif( $category_id==1) {
    					$wp_query->query_vars['posts_per_page'] = 1;
    				}
    			}
    		}
    
    	return $wp_query;
    }

    But it still doesn't work. The strange thing:
    the alert() function works and display the category id.

    Please help...

  3. manuelmasia
    Member
    Posted 3 years ago #

    Sorry... my fault! There was a conflict with another function... it works! But in the second way, not the first.

    Bye

Topic Closed

This topic has been closed to new replies.

About this Topic