ショートコードで記事一覧を出力する:WordPress
WordPressの投稿や固定ページ内で記事一覧を表示する際にショートコードを使用する方法です。
functions.php内に
// ショートコードの指定 -> [getList num="x" cat="y" id="z"]
function getListItems($atts, $content = null) {
//デフォルト指定
extract(shortcode_atts(array(
"num" => '3',
"cat" => '1',
"id" => ''
), $atts));
global $post;
$oldpost = $post;
// 記事データ取得
$myposts = get_posts('numberposts='.$num.'&order=DESC&include='.$id.'&orderby=post_date&category='.$cat);
if($myposts) {
// 記事がある場合↓
$retHtml = '<ul class="sbloglist">';
foreach($myposts as $post) :
// 投稿ごとの区切り
$retHtml .= '<li>';
setup_postdata($post);
// アイキャッチ画像の有無
if ( has_post_thumbnail() ) {
// アイキャッチ画像有
$retHtml .= '<div class="pic">' . get_the_post_thumbnail($page->ID, 'full') . '</div>';
} else {
// アイキャッチ画像無し
$retHtml .= '';
}
// 文章のみのエリアをdivで囲う
$retHtml .= '<div class="txt">';
// 年月日を取得
$year = get_the_time('Y');
$month = get_the_time('n');
$day = get_the_time('j');
$retHtml .= '<p class="day">' . $year . '年' . $month . '月' . $day . '日</p>';
// タイトル取得
$retHtml.= '<p class="pttl">';
$retHtml.= '<a href="' . get_permalink() . '">' . the_title("","",false) . '</a>';
$retHtml.= '</p>';
// 抜粋を取得
$getString = get_the_excerpt();
$retHtml.= '<div class="getPostContent">' . $getString . '</div>';
$retHtml.= '</li>';
endforeach;
$retHtml.= '</ul>';
} else {
$retHtml='<p>記事がありません。</p>';
}
$post = $oldpost;
return $retHtml;
}
// 呼び出し指定
add_shortcode("getList", "getListItems");
を追加
あとは投稿内の好きな位置に
[getList num=”4″ cat=”2″ id=”5″]
等のように追加するだけでOK。
WordPressのおすすめ参考書
bookfan 1号店 楽天市場店
¥3,300 (2026/01/04 15:36時点 | 楽天市場調べ)

