Last update at :2024-02-07,Edit by888u
When we are building a website, sometimes in order to display a beautiful effect, we need to implement a homepage and a different number of articles displayed on the category page:
The number of articles displayed on each WordPress page is specified in the background settings, and will be applied to the blog list page (usually the homepage), 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 will not apply to each page. To specify the number of articles displayed on each page according to the page type, you need to write code to implement it.
Modifying the number of articles displayed on each page means modifying the posts_per_page parameter,
Recommended method: Put the following code into functions.php to achieve it
function custom_posts_per_page($query){ if(is_home()){ $query->set('posts_per_page',8);//The home page displays 8 articles per page } if(is_search()){ $query->set('posts_per_page',-1);//The search page displays all matching articles without pagination } if(is_archive()){ $query->set('posts_per_page',25);//archive displays 25 articles per page } } add_action('pre_get_posts','custom_posts_per_page');With WordPress conditional tags, you can extend this code however you want.
Deprecated method
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' );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.
Recommended site searches: domain name registration, registration system, large bandwidth server rental, virtual host evaluation, domain name information, foreign space service providers, which Hong Kong space is better, domain name price, website space rental, domain name query official website,
发表评论