워드프레스에서 두 카테고리에 모두 속하는 글을 쿼리하는 방법

Last Updated: 2015년 09월 24일 | | 댓글 남기기

워드프레스에서 두 카테고리에 동시에 속하는 글들을 표시하고 싶은 경우가 있을 수 있습니다. 이 경우 다음과 같은 쿼리를 사용하여 구현할 수 있습니다. 아래와 비슷한 코드를 테마 파일의 적절한 곳에 추가하면 됩니다.

<?php
$my_query_args = array(
'posts_per_page' => 6,
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => array( 10, 11 ),
'operator' => 'AND'
)
)
);

$my_query = new WP_Query( $my_query_args );

if( $my_query->have_posts() ) : while( $my_query->have_posts() ) : $my_query->the_post(); ?>

<li>
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(array(230,192)); ?></a>
</li>
<?php endwhile; endif; wp_reset_postdata(); ?>
// Source: wordpress.stackexchange.com

WP Query에서 query_posts()tax_query를 참고하시기 바랍니다.

위의 경우는 두 카테고리에 동시에 속하는 경우를 고려한 것인데요, 그렇지 않은 경우 query_posts()를 사용할 수 있습니다.

<?php
query_posts('category_name=team&order=asc');
if ( have_posts() ) : while( have_posts() ) : the_post();
?>
<div class="span3">
<div class="pic">
<?php if (( function_exists('has_post_thumbnail') ) && ( has_post_thumbnail() )) {
the_post_thumbnail('thumbnail');
} else { ?>
<img src="<?php echo get_template_directory_uri(); ?>/img/no-thumbnail.jpg" width="260" height="260">
<?php } ?>
</div>
<div class="id">
<h3><?php the_title(); ?></h3>
<?php the_content(); ?>
</div>
</div>
<?php endwhile; else: ?>
<p><?php _e( 'No content was found', 'criativia' ); ?></p>
<?php endif; ?>
// Source: wordpress.org

두 개 이상의 카테고리(OR로)를 쿼리할 경우에는 $query = new WP_Query( 'cat=9,11' );와 같은 형태를 사용할 수 있습니다(참고).

 

 


댓글 남기기

Leave a Comment