HTML,CSS,PHP,ワードプレスカスタマイズ 技術情報資料

ワードプレス よく使う 投稿表示ループのひな形

ワードプレスでいろいろやってるといっつも使うパターンがあるのでひな形にしました。

ワードプレスでよく使う「投稿表示ループのひな形」

ご利用ください。

<?php
$max = 4; // 横並びの時 カラム数を設定
$args = array(
'post_type' => $post_type,
'cat' => ", // カテゴリーを指定する場合 複数個指定 '1,2,3'
'post_status' => 'publish', // 公開中のものだけ
'posts_per_page' => -1, // 表示最大件数 : 全件 -1
'orderby' => 'date', // 表示順並び替えキー項目
'order' => 'DSEM' // 表示順 ASEM 小さい方から(古いものから)
);
$the_query = new WP_Query( $args );
if( $the_query->have_posts() ){
$cat = get_the_category();
$category = $cat[0]->cat_name;
$count = 0;
?>
<!-- LOOP 外側 タグ --->
<ul class="side-newsList pl-5">
<!-- /LOOP 外側 タグ --->
<?php
while( $the_query->have_posts() ) {
$the_query->the_post();
$date = get_the_time('Y/n/j'); // 書式付
if( has_post_thumbnail() ) {
$thumb_id = get_post_thumbnail_id();
$thumb_url = wp_get_attachment_image_src($thumb_id);
$thumb_url = $thumb_url[0];//[0] => url [1] => width [2] => height [3] => true:リサイズ済み false:元のサイズ
} else {
$thumb_url = $the_query->no_thumb_image();
}
$the_content = get_the_content();
$count++;
if($count>$max){
?>
<!-- 横並びの時ここに /div などの rows end タグ -->
<!-- 横並びの時ここに 次の rows の div などの開始タグ -->
<?php
}
// $count : 番号
// $category : カテゴリー名
// $date : 日付
// get_permalink() : パーマリンク
// get_the_title() : タイトル
// $thumb_url : サムネイル URL
// $the_content : コンテンツ (切り取り: mb_strimwidth($the_content,0,intval('切り取り字数'));
//—– ↓本体 —-
?>
<li>
</li>
<?php
//—– ↑本体 —-
} // while
if($count!=0){
?>
<!-- 横並びの時ここに rows の /div などの終了タグ -->
<?php
}
?>
<!-- LOOP 終了 タグ -->
</ul>
<!-- /LOOP 終了 タグ -->
<?php
} // if( $the_query->have_posts() ) :
wp_reset_postdata();
?>


$args に投稿の抽出条件を設定します。一応いろいろ書いていますけど、基本は、

$args = array(
'cat' => $cat, // カテゴリーを指定する場合 複数個指定 array(1,2,3)
'post_status' => 'publish', // 公開中のものだけ
'posts_per_page' => $number, // 表示最大件数 : 全件 -1
'order' => 'DESC' // 表示順 ASEM
);

ぐらいで足りると思います。

ul を基本としているので、データ表示部は li で出力を想定しています。

スポンサーリンク

スポンサーリンク

カテゴリー