クエリ を カスタマイズ して 表示する
この記事は 2015年 6月 24日 に書かれた記事です。
この記事は WordPress Version 4.2.2 の時の記事です。
TOPページに 投稿の一部を 表示させる なんてことは よくある話です。
そんな時は WP_Query を 使って 自由に 一覧を表示しちゃいましょう!!
まずは 最新の投稿を 3件だけ 表示する と いうものです。
トップページ で よく使うコードですね!!
<?php
$args = array(
'posts_per_page' => 3,
);
$the_query = new WP_Query( $args );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ) :
$the_query->the_post();
?>
<section class="well">
<header>
<h1><?php the_title(); ?></h1>
</header>
<time datetime="<?php the_time( 'Y-m-d' ); ?>"><?php the_time( get_option( 'date_format' ) ); ?></time>
<main>
<?php the_excerpt(); ?>
</main>
<a href="<?php the_permalink(); ?>">詳細ヘ »</a>
</section>
<?php
endwhile;
endif;
wp_reset_postdata();
?>
次に カスタム投稿 (custom_post) を すべて表示する という コードです。
<?php
$args = array(
'post_type' => 'custom_post',
'posts_per_page' => -1,
);
$the_query = new WP_Query( $args );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ) :
$the_query->the_post();
?>
<section class="well">
<header>
<h1><?php the_title(); ?></h1>
</header>
<time datetime="<?php the_time( 'Y-m-d' ); ?>"><?php the_time( get_option( 'date_format' ) ); ?></time>
<main>
<?php the_excerpt(); ?>
</main>
<a href="<?php the_permalink(); ?>">詳細ヘ »</a>
</section>
<?php
endwhile;
endif;
wp_reset_postdata();
?>
最後に カスタム投稿 (custom_post) 内の
カスタムフィールド の キー (group) に の A か B が 含まれ
かつ
カスタムタクソノミー (custom_tax) の スラッグ が (hoge)
で 絞り込んだ結果を 5件表示する という コードです。
<?php
$args = array(
'post_type' => 'custom_post',
'posts_per_page' => 5,
'meta_query' => array(
array(
'key' => 'group',
'value' => array( 'A', 'B' ),
),
),
'tax_query' => array(
array(
'taxonomy' => 'custom_tax',
'field' => 'slug',
'terms' => 'hoge',
),
),
);
$the_query = new WP_Query( $args );
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ) :
$the_query->the_post();
?>
<section class="well">
<header>
<h1><?php the_title(); ?></h1>
</header>
<time datetime="<?php the_time( 'Y-m-d' ); ?>"><?php the_time( get_option( 'date_format' ) ); ?></time>
<main>
<?php the_excerpt(); ?>
</main>
<a href="<?php the_permalink(); ?>">詳細ヘ »</a>
</section>
<?php
endwhile;
endif;
wp_reset_postdata();
?>
これで 大抵 使いまわせますね!!
I referred to notnil creation weblog.
http://notnil-creative.com/blog/archives/1288