M
M
miron-partner2018-07-25 08:20:39
WordPress
miron-partner, 2018-07-25 08:20:39

How to set the number of posts to display for Wordpress custom post type archives?

Hello. I need to set, for a particular custom post type type, the number of posts to display for the Archives page (for all taxonomies of that custom post type type). On the Internet, I found the following code to insert into functions.php:

function custom_posts_per_page($query){
    if(is_post_type_archive() || is_tax()){  //количество записей в пользовательстком типе записей и в пользовательских таксономиях
    $query->set('posts_per_page',50);
    }
}
add_action('pre_get_posts','custom_posts_per_page');

Everything works fine, only on the pages of the same archives I have a widget for displaying the latest entries, and it also starts displaying the last 50 entries. If the above code is not implemented in functions.php, then everything works as expected:
- 10 posts are displayed in the archives (as set in the admin panel)
- 5 posts are displayed in the widget (last posts) as set in the widget settings.
That is, before inserting the code into functions.php, the number of output entries in the widget and in the archives is different (as indicated in the settings for each of them), and when I insert the above code, it sets the number for all cycles on the page, be it archive entries or recent entries.
Brief question:How to set the number of displayed posts for archive pages (custom post types) so that the widget settings do not break and display as many posts as specified in the widget settings?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
miron-partner, 2018-07-25
@miron-partner

This is how it worked as it should:

function custom_posts_per_page($query){
    if(!is_admin() && $query->is_main_query() && is_post_type_archive()){ //количество записей в пользовательстком типе записей
    $query->set('posts_per_page',50);
    }
   if(!is_admin() && $query->is_main_query() && is_tax()){ //количество записей в пользовательстком типе записей в таксономиях
    $query->set('posts_per_page',50);
    }
}
add_action('pre_get_posts','custom_posts_per_page');

Y
Yunus Gaziev, 2018-07-25
@BBoyJuss

Try adding a condition to change the query

if ( is_post_type_archive( 'название кастомного типа products например' )  ) {
    // ...
}

In general, the is_post_type_archive() , is_tax() condition needs to be improved . You can pass qualifying arguments for each check.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question