wordpressでカテゴリーが大量にあり、そのそれぞれからあちこちに、最新1件を表示するというお仕事がありまして・・・・何度もループを書くのは面倒な上、コードが見づらくなるので、ショートコード化しました。
下記の記事を参考にしてベースを作成し、レイアウト違いのショートコードがいくつか欲しかったので、出力側はget_template_partで読み込ませる仕様に変更しました。
呼び出すショートコードは、
[getCategoryArticle num=”1″ cat=”topic1″ layout=”normal”]
num | 表示する記事数 |
---|---|
cat | カテゴリースラッグ |
layout | 呼び出すテンプレート名、loop-●●の●●の部分 |
あとは、loop-●●.phpをレイアウトの種類分作っておけばOKです。だいぶコードのシェイプアップになりました・・
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//ショートコードで記事一覧を表示 | |
//<?php | |
// 一覧記事取得関数 -------------------------------------------------------------------------------- | |
// "num" = 表示記事数, "cat" = カテゴリ番号, "layout" = レイアウトテンプレート(loop-●●.php) | |
// 呼び出し元での指定も可能 -> [getCategoryArticle num="x" cat="y" layout="z"] | |
function getCatItems($atts, $content = null) { | |
extract(shortcode_atts(array( | |
"num" => '2', | |
"cat" => '12', | |
"layout" => 'normal' | |
), $atts)); | |
// 処理中のpost変数をoldpost変数に退避 | |
global $post; | |
$oldpost = $post; | |
// カテゴリーの記事データ取得 | |
$myposts = get_posts('numberposts='.$num.'&order=DESC&orderby=post_date&category_name='.$cat); | |
if($myposts) { | |
// 取得した記事の個数分繰り返す | |
foreach($myposts as $post) : | |
get_template_part('loop',$layout); | |
endforeach; | |
} else { | |
// 記事がない場合↓ | |
$retHtml='<p>記事がありません。</p>'; | |
} | |
// oldpost変数をpost変数に戻す | |
$post = $oldpost; | |
return $retHtml; | |
} | |
// 呼び出しの指定 | |
add_shortcode("getCategoryArticle", "getCatItems"); |