Pergunta

I have a custom post type 'portfolio' and different WP_Query for different custom post pages and purposes.

For portfolio page I want to select 12 posts_per_page of portfolio type.

For main page I want to select 8 posts_per_page of portfolio type.

For block Similar Works on Single work page I want to select 4 posts_per_page of portfolio type.

At the moment in all wp_query I have a var $posts_per_page for this number. But it doesn't work, because I added a function in functions.php for defining a default custom portfolio posts per page value. And it's 8. So now I have 8 posts per page in all queries. The reason I added this function was to make a pagination to work. That function:

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

Should I just remove this function and change Blog posts per page var in admin panel of Wordpress to 1? Like it was before. Or is there another solution to this issue?

UPDATE

I was trying to change the function into this, but then wordpress doesn't work at all:

function portfolio_posts_per_page( $query ) {

if ( $query->query_vars['post_type'] == 'portfolio' ) {

        if ( is_post_type_archive('portfolio') 
            $query->query_vars['posts_per_page'] = 12;
        }
        elseif (is_front_page()) {
            $query->query_vars['posts_per_page'] = 8;
        }
        elseif ( is_singular( 'portfolio' ) ) {
            $query->query_vars['posts_per_page'] = 4;
        }
        else {
            $query->query_vars['posts_per_page'] = 4;
        }
}       
return $query;
}
Foi útil?

Solução

For each of your custom post types, the template files use a custom query; for example, if you have a custom template named archive-portfolio then use something like this in that file:

$args = array( 'post_type' => 'portfolio', 'posts_per_page' => 8 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
    the_title();
    echo '<div class="entry-content">';
        the_content();
    echo '</div>';
endwhile;

This is just an example, same way, you use a different template file for another custom post type and use completely different arguments. For the main query on home page, you may set up on WordPress backend. Read more on Codex.

Update: Check this answer of mine for pre_get_posts.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top