ショートコードでタグを指定して投稿一覧を表示:WordPress
最終更新日:
ショートコードで投稿タグを指定して投稿一覧を表示する方法をメモ
実装
functions.phpに
//[taglist num="5" id="1,2" exclude="4"]
function getMyTagPosts($atts) {
extract(shortcode_atts(array(
"num" => '9999', //記事の取得数
"id" => '',
"exclude" => ''
), $atts));
global $post;
$tag_id = explode(',', $atts['id']);
$exclude_id = explode(',', $atts['exclude']);
$myposts = get_posts(array(
'tag__in' => $tag_id,
'numberposts' => $atts['num'],
'exclude' => $exclude_id,
'order' => 'DESC',
'post_type' => 'post'
));
if($myposts){
$retHtml.='<ul class="tagpostlist">';
foreach($myposts as $post) :
setup_postdata($post);
//アイキャッチ画像
$image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), "full" );//thumbnail, medium, large, full
list( $src, $width, $height ) = $image;
//アイキャッチ画像がない場合
if($src == ""){
$src = "https://kinmaweb.jp/jansou-kensaku/wp-content/themes/kinma/img/noimage.jpg";
}
$retHtml.='<li"><a href="'.get_permalink().'">';
$retHtml.='<div class="pic"><img src="'.$src.'" alt="" class="responsive" /></div>';
$retHtml.='<p class="ttl">'.get_the_title().'</p>';
$retHtml.='<div class="morebtn"><a href="'. get_permalink().'">詳細をみる</a></div>';
$retHtml.='</a></li>';
endforeach;
$retHtml.='</ul>';
wp_reset_postdata();
}else{
$retHtml='<p class="none">投稿がありません。</p>';
}
return $retHtml;
}
add_shortcode("taglist", "getMyTagPosts");
でOK
タグIDで投稿を指定
タグIDで投稿を指定する場合は
[taglist id=”3″]
のように指定
複数の場合は,カンマ区切りで
その他の指定
たとえば
[taglist num=”5″ id=”1,2″ exclude=”4″]
とすると
タグIDが1と2の記事で投稿IDが4の記事を除外したリストを最大5件表示
という感じになります。
WordPressのおすすめ参考書
bookfan 1号店 楽天市場店
¥3,300 (2025/11/01 09:38時点 | 楽天市場調べ)


