코딩

워드프레스 Custom Query 사용하여 홈페이지 꾸미기

코딩저니 렉스 2022. 12. 16. 16:08

Custom Query를 사용하여 홈페이지를 꾸미는 방법

워드프레스에서는 특정한 Php 코드와 관련하여 지금 있는 url 및 페이지 주소에 따라 자동으로 불러오는 기능들이 있습니다.

예를 들어, have_posts(); 기능을 그냥 사용하게 되면 해당 페이지에 있는 포스트들만 불러오게 된다.

볼르그 (/blog) 페이지에서는 잘 작동할 수 있지만 홈페이지에서는 블로그 포스트가 없기 때문에 제대로 불러오지 않을 수 있습니다.

따라서 Custom Query를 사용해서 해당 페이지가 아니더라도 원하는 기능을 불러오게 될 수 있습니다.

div class="full-width-split__two">
<div class="full-width-split__inner">
<h2 class="headline headline--small-plus t-center">From Our Blogs</h2>
<?php
$homepagePosts = new WP_Query(array(
'posts_per_page' => 2,
));
 불러오게 될 수 있습니다.
while loop에서 보통 have_posts()기능만 사용하지만 그럼 아무것도 안뜨기 때문에 홈페이지에서는 $homepagePosts variable을 사용해서 미리 만든 custom query를 사용해 주고 있습니다.

아래 사용된 php 코드에 대한 설명 <?php ?>

the_permalink();드 = 페이지/포스트의 url 주소 불러옴

the_time('M') = 월 정보를 불러옴

the_time('d') = 날짜 정보를 불러옴

the_title(); = 제목 정보를 불러옴

wp_trim_words(); = 블로그 포스트의 내용을 불러오지만 몇 단어로 짜를지(trim) 설정할 수 있습니다. ()괄호 안에 2가지 조건 값(argument)을 넣어줘야 함.

  • get_the_content(), 18 = 포스트의 컨텐츠를 가지고 오고, 18단어만 표시한다. 
while ($homepagePosts->have_posts()) {
$homepagePosts->the_post(); ?>
<div class="event-summary">
<a class="event-summary__date event-summary__date--beige t-center" href="<?php the_permalink(); ?>">
<span class="event-summary__month"><?php the_time('M'); ?></span>
<span class="event-summary__day"><?php the_time('d'); ?></span>
</a>
<div class="event-summary__content">
<h5 class="event-summary__title headline headline--tiny"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h5>
<p><?php echo wp_trim_words(get_the_content(), 18); ?> <a href="<?php the_permalink(); ?>" class="nu gray">Read more</a></p>
</div>
</div>

<?php } wp_reset_postdata();
?>
 

Custom Query를 사용하여 홈페이지를 꾸미는 방법을 아래서 확인할 수 있습니다.

스타일링은 연습 템플릿 파일에 있는 div class html 코드를 가지고 와서 사용하였습니다.

강사의 유의사항:

아래 php코드를 사용하여 워드프레스의 데이터를 모두 리셋하도록 하는 것이 좋은 습관이라고 하였습니다. 

정확히 어떤 기능인지는 모르겠지만 유익한 기능이기 때문에 습관적으로 아래 코드를 넣어주는 것이 좋다고 합니다.

<?php } wp_reset_postdata(); ?>