Home > CMS Tutorial > WordPress > body text

How to manually customize the number of articles displayed in WordPress

藏色散人
Release: 2020-06-18 13:29:22
forward
3431 people have browsed it

The following column WordPress Tips will introduce you to the detailed method of manually customizing the number of articles displayed in WordPress. I hope it will be helpful to friends in need!

How to manually customize the number of articles displayed in WordPress

WordPressThe number of articles displayed per page is specified in the background reading settings and will be applied to the blog list page (usually Home page), search page, tag page, category page and time index page. The structure of adding these pages is different. For example, some display the title and abstract, and some only display the title, so specifying the same number of pages does not apply to each page. page. To specify the number of articles displayed on each page according to the page type, you need to write code to implement it.

Recommended method

Modify the number of articles displayed on each page, that is, modify the posts_per_page parameter, and put the following code into functions.php to achieve this. The code comes from WordPress Answers.

function custom_posts_per_page($query){
    if(is_home()){
    $query->set('posts_per_page',8);//首页每页显示8篇文章
    }
    if(is_search()){
        $query->set('posts_per_page',-1);//搜索页显示所有匹配的文章,不分页
    }
    if(is_archive()){
        $query->set('posts_per_page',25);//archive每页显示25篇文章
}//endif
}//function
 
//this adds the function above to the 'pre_get_posts' action    
add_action('pre_get_posts','custom_posts_per_page');
Copy after login

With WordPress’ conditional tags, you can extend this code arbitrarily.

Method not recommended

It is not recommended to modify the theme template directly, for example, use query_posts before the index.php main loop to change the number of articles displayed on each page

query_posts( 'posts_per_page=5' );
Copy after login

Disadvantages:

First, increase the number of queries

Second, the flexibility is not high. If categories and tags have their own templates, you need to repeat the query_posts trick in those templates.

Third, you need to be particularly careful when using query_posts. If you forget to restore the global variable, inexplicable errors may occur.

The above is the detailed content of How to manually customize the number of articles displayed in WordPress. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template