LoginSignup
0
3

More than 5 years have passed since last update.

WP_Queryの使い方(パラメーター)

Last updated at Posted at 2017-11-17

意図した投稿データを出力するための便利タグであるWP_Queryの使い方とパラメーターの使い方を紹介します。
以下では今まで使ったものを記述していきます。

投稿タイプを指定する

・投稿タイプ名には任意の文字を入力してください。
・post_type指定をarrayにすることで複数設定をすることができます。

php
$args = array( 
    'post_type' => array( 
            '投稿タイプ名'
            ),//投稿タイプ名(複数入力可能)
    'posts_per_page' => 6   //投稿数
    );

    $the_query = new WP_Query( $args );

     if ($the_query->have_posts()) : 
     $count = 1;
     while ($the_query->have_posts()) : 
         $the_query->the_post();

       the_content();

     $count++;
     endwhile;
  endif;
wp_reset_postdata();

タクソノミーのタームを指定する

php
$args = array( 
'tax_query' => array(
   'relation' => 'OR',     
    array(
          'taxonomy' => 'タクソノミー名',
           'terms' => array( 'ターム名その1', 'ターム名その2'),
           'field' => 'slug',
           'operator' => 'IN',
        ),
       ),
    'posts_per_page' => 4,
    );
    $the_query = new WP_Query( $args);
        if ($the_query->have_posts()) : 
           while ($the_query->have_posts()) : 
             $the_query->the_post();

           the_content();
           endwhile;
    endif;
wp_reset_postdata();

タクソノミーの指定タームを除外する

php
$args = array( 
    'post_type' => '投稿タイプ名',
    'tax_query' => array(
        'relation' => 'AND',
            array(
                'taxonomy' => 'タクソノミー名',
                'terms' => array('ターム名その1'),
                'field' => 'slug',
                'operator' => 'NOT IN',
            ),
        ),
    'posts_per_page' => 4,
    );
    $the_query = new WP_Query( $args);
        if ($the_query->have_posts()) : 
           while ($the_query->have_posts()) : 
             $the_query->the_post();

           the_title();

           endwhile;
    endif;
wp_reset_postdata();

参考サイト
WP_Queryの使い方をPHPコードにまとめた便利なコード・スニペット

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3