워드프레스에서 홈페이지/검색/아카이브 페이지에 표시되는 글 개수 변경하기

워드프레스 정보를 제공하는 블로그 Avada 2018. 10. 4. 13:57 • 댓글:

워드프레스

워드프레스에서 홈페이지(최신 글을 표시하도록 설정한 경우), 검색 페이지, 아카이브 페이지(카테고리 페이지 등)에 표시되는 글 개수를 달리 설정하고 싶은 경우 'pre_get_posts' 액션을 사용하면 됩니다.

function custom_posts_per_page($query) {
    if (is_home()) {  // 블로그 페이지
        $query->set('posts_per_page', 8); 
    }
    if (is_search()) { // 검색 페이지
        $query->set('posts_per_page', -1); 
    }
    if (is_archive()) { // 아카이브 페이지
        $query->set('posts_per_page', 25); 
    } //endif
} //function
//this adds the function above to the 'pre_get_posts' action    
add_action('pre_get_posts', 'custom_posts_per_page');
// 출처: Show a different number of posts per page depending on context (e.g., homepage, search, archive)

카테고리에 표시되는 글 개수를 변경하려는 경우에도 마찬가지 방법으로 가능합니다.

아바다(Avada)엔폴드(Enfold) 등 많은 유료 테마에서는 자체 페이지 빌더를 사용하거나 Visual Composer 페이지 빌더를 사용하여 페이지를 만들 수 있습니다. 전면 페이지나 특정 페이지에 페이지 빌더를 사용하여 글 개수를 설정한 경우에는 페이지 빌더 내에서 수정해주도록 합니다.

테마 파일을 직접 수정한 경우에는 while(have_posts()) 조건에서 글 개수를 제한하도록 수정하면 됩니다.

예시:

<?php $i = 1; while (have_posts() && $i < 6) : the_post(); ?>
 <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
 <p>?php the_time(); ?></p>
 <?php the_content(); ?>
 <p><?php the_tags(); ?></p>
<?php $i++; endwhile; ?>
 <p><?php next_posts_link(); ?></p>
 <p><?php previous_posts_link(); ?></p>
<?php else : ?>
 <h1>Not Found</h1>
 <p>Silly monkey.</p>
<?php endif; ?>
// 출처: Two Ways to Limit the Number of Posts without a Plugin (플러그인 없이 글 개수를 제한하는 두 가지 방법)

참고할 만한 문서:

  • https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts