KH-WEBLOG TOP > WEBメモ > WordPress > ショートコードで記事一覧を出力する:WordPress

ショートコードで記事一覧を出力する: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化作業を代行します

WordPressのおすすめ参考書

楽天Kobo電子書籍ストア
¥3,278 (2024/04/12 09:44時点 | 楽天市場調べ)

TAGS

.htaccess ActionScript All in one seo pack Contact Form 7 CSS CSS3 EC-CUBE Flash HTML HTML5 JavaScript jQuery LightBox PHP RSS SEO WordPress アイキャッチ画像 アクセス解析 カスタムフィールド カテゴリー カラーミーショップ カート コメント ショートコード テンプレートタグ ドロップダウンメニュー パーマリンク フォーム フルスクリーン ブログカード プラグイン ページテンプレート ページナビ ページ分割 マウスイベント リダイレクト リンク リンクカード レンタルサーバー ロールオーバー 携帯サイト 条件分岐 正規表現 関連記事