WP_Query または get_posts で、ワードプレスのカスタム投稿タイプのデータを取得したいとき(簡易)
投稿: 更新:2017/11/07
カスタム投稿タイプの記事一覧を取り出したい
取り出したい投稿は、ポストタイプ 「news」の記事を、1ページ当たり10件、最新のものから更新日順で、公開されたもののみ取り出したい場合。
1. 記事の取得条件を記述
まずは、以下のように取得する条件を記述します。
| 1 2 3 4 5 6 7 | $args = array(   'post_type' => 'news',       //ポストタイプ名 通常の投稿の場合は post   'posts_per_page' => 10,      //1ページの表示数   'orderby' => 'modified',     //並べ替えの項目   'order' => 'DESC',           //並び順   'post_status' => 'publish'   //公開記事 ); | 
WP_Query を使用する場合の記述
wp_query を使用して、記事を取得する場合は、以下のように記述します。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | //取得条件 $args = array(   'post_type' => 'news',       //ポストタイプ名 通常の投稿の場合は post   'posts_per_page' => 10,      //1ページの表示数   'orderby' => 'modified',     //並べ替えの項目   'order' => 'DESC',           //並び順   'post_status' => 'publish'   //公開記事 ); //Wp_Queryの場合 $the_query = new WP_Query($args); if ($the_query->have_posts()) :   while ($the_query->have_posts()) : $the_query->the_post();   //ここに処理   echo '<h2>' . get_the_title() . '</h2>';//タイトル   the_content(); //本文   //処理END   endwhile;   wp_reset_postdata(); endif; | 
get_posts を使用する場合の記述
get_posts を使用して、記事を取得する場合は、以下のように記述します。
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | //取得条件 $args = array(   'post_type' => 'news',       //ポストタイプ名 通常の投稿の場合は post   'posts_per_page' => 10,      //1ページの表示数   'orderby' => 'modified',     //並べ替えの項目   'order' => 'DESC',           //並び順   'post_status' => 'publish'   //公開記事 ); //get_postsの場合 $the_query = get_posts($args); if($the_query) :   foreach ($the_query as $post) : setup_postdata($post);   //ここに処理   echo '<h2>' . get_the_title() . '</h2>';//タイトル   the_content(); //本文   //処理END   endforeach;    wp_reset_postdata(); endif; | 
どちらでも処理的には変わりがありません。
取得したい内容を細かく指定したい場合は、WP_Query が良いかと思います。
Codex 関数リファレンス/WP Query
必要に応じて、お好きなほうを。
