Question

I'd like to know if I can remove the limit on the posts_per_page for a specific post type.

In the archive.php page I'm displaying different post type, and for the specific "publications" post type I want to display all the posts. How can I achieve this without impacting the traditional "post" type?

Was it helpful?

Solution

You can hook into the pre_get_posts action, to access the $query object.

You should use your action hook inside your functions.php. An example of what your function could look like:

add_action( 'pre_get_posts', 'publications_archive_query' );
function publications_archive_query( $query ) {
  if ( !is_admin() && $query->is_main_query()) {
    if ( $query->get('post_type') === 'publications' ) {
      $query->set( 'posts_per_page', 5 );
    }
}

Narrow down what is the query you are modifying by using conditional checks.

$query->get('post_type') to get current's Query post_type to check against.

is_main_query to make sure you are only applying your query modification to the main query.

Read further and find more examples: https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts

OTHER TIPS

Accepted answer isn't working, but this one does:

function bloom_custom_posts_per_page( $query ) {
  if( !is_admin() && $query->query_vars['post_type'] == 'post_type') {
     $query->query_vars['posts_per_page'] = -1;
     return $query;
  }
}
add_filter( 'pre_get_posts', 'bloom_custom_posts_per_page' );

If you are creating the query yourself inside those .php pages, then it's better to pass -1 in argument to obtain unlimited posts:

$args =  array( ...... 'posts_per_page'=>-1, .....) 
$your_query = new WP_Query($args);

If you dont have access to the query-creating .php file, then you might neeed to use less-recommended pre_get_post version (which affects all pages/queries with that custom-type), like @FFrewin suggested.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top