WordPressでWP_Queryまたは、get_postsのループを使った記事一覧(基本情報)を表示する方法。
※ページネーションなし
基本項目を取得表示するためのサンプルコード
※コメントアウトしてる方をがget_posts用
// 設定 // 取得記事 // 日付、ソート // 日付、降順 // ポストタイプ、postやカスタム投稿タイプなど $def['posts_per_page'] = 5; $def['orderby'] = 'date'; $def['order'] = 'DESC'; $def['post_type'] = 'カスタム投稿など'; $args = array( 'posts_per_page' => $def['posts_per_page'], 'orderby' => $def['orderby'], 'order' => $def['order'], 'post_type' => $def['post_type'], 'cat' => 1, //カテゴリー表示 ); //ポストデータ取得 //WP_Queryでデータ取得すると総ページ数を取得できる。 $myposts = new WP_Query($args); //get_posts()の場合 //$myposts = get_posts($args); //以下、取得したデータの処理 if($myposts->have_posts()) { //get_posts()の場合 //if(count($myposts)>0) { //記事のループ処理whileにあたる部分 foreach($myposts->posts as $post){ //get_posts()の場合 //foreach($myposts as $post){ //ポストID //$post->ID //投稿記事リンク $permalink = get_permalink( $post->ID ); echo $permalink; //投稿記事タイトル echo $post->post_title; //投稿日付 $post_date = date("Y年h月j日",strtotime($post->post_date)); echo $post_date; //投稿内容 echo $post->post_content; //カテゴリー名 $category = get_the_category( $post->ID ); echo $category[0]->name; //カスタムフィールドを取得したい場合 //get_post_meta($post->ID, 'カスタムフィールド名', true); //アイキャッチ画像URL echo get_the_post_thumbnail( $post->ID, 'full' ); } } wp_reset_query();
ページネーションを追加したい場合はWordPressのWP_Query(get_posts)でループした時のページネーションへのデータ引継ぎ方を参照。