WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Limit post per search page (6 posts)

  1. werlisa
    Member
    Posted 4 years ago #

    I found this code that lets you limit the number of post in the categories, I wonder if you can do the same but for the search results.

    for categories:

    function limit_posts_per_page() {
    	if ( is_category() )
    		return 2;
    	else
    		return 5; // default: 5 posts per page
    }
    add_filter('pre_option_posts_per_page', 'limit_posts_per_page');

    for archive page:

    function limit_posts_per_archive_page() {
    	if ( is_category() )
    		set_query_var('posts_per_archive_page', 2); // or use variable key: posts_per_page
    }
    add_filter('pre_get_posts', 'limit_posts_per_archive_page');

    Source: http://zeo.my/wordpress-limit-posts-per-page/

    Regards

  2. Safirul Alredha
    Member
    Posted 4 years ago #

    Just change is_category() to is_search(), works for most conditional tags.

    btw, better to use the 2nd method.

  3. werlisa
    Member
    Posted 4 years ago #

    For the categories runs smoothly but when replaced by is_search () the site stops working and the screen is blank .. I did something wrong?

    function limit_posts_per_archive_page() {
    	if ( is_search() )
    		set_query_var('posts_per_archive_page', 10); // or use variable key: posts_per_page
    }
    add_filter('pre_get_posts', 'limit_posts_per_archive_page');
  4. Safirul Alredha
    Member
    Posted 4 years ago #

    Did u use same name function? If yes, merge into a single function. Example:

    function limit_posts_per_archive_page() {
    	if ( is_category() )
    		$limit = 2;
    	elseif ( is_search() )
    		$limit = 1;
    	else
    		$limit = get_option('posts_per_page');
    
    	set_query_var('posts_per_archive_page', $limit);
    }
    add_filter('pre_get_posts', 'limit_posts_per_archive_page');
  5. werlisa
    Member
    Posted 4 years ago #

    Perfect! Has been a great help for me, I really thank you very much.

    Greetings Zeo!

  6. bekar09
    Member
    Posted 3 years ago #

    I am somehow unable to get this work. I tried with Safirul Alredha's code on WP 3.1

Topic Closed

This topic has been closed to new replies.

About this Topic