てくてくあるく

WordPress の テーマ とか プラグイン に ついて 勉強しています

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();
?>

これで 大抵 使いまわせますね!!


notnil creation weblogを参考にさせていただきました。
http://notnil-creative.com/blog/archives/1288

Related Article

テーマ を アップデート しました

詳細へ »

スパムコメント対策 に DISQUS を 導入 してみた

詳細へ »

WordPress の CSS JS を 非同期 で 読み込む

詳細へ »