特定カテゴリに紐付いた画像を取得する

記事に紐付いた画像ではなく、特定カテゴリに紐付いた画像の取得方法をご紹介します。
ただし、負荷対策のため全件を出力するわけではなく、特定カテゴリ内の新着num件の記事を対象に紐付いている画像を取得して返します。

では、サンプルコードです。
まずは、テンプレートのfunctions.phpに以下の関数を記述してください。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
function getCatImage($cat,$num = null){
    if($cat == null){ return(null); }
     
    if($num != null && ereg("^([0-9]+)$",$num)){
        $get_parm = 'numberposts='.$num.'&order=DESC&orderby=post_date&category='.$cat;
    }else{
        // 件数が指定されていない場合はWordPressの既定値(5件)が適用される
        $get_parm = 'order=DESC&orderby=post_date&category='.$cat;
    }
    $myposts = get_posts($get_parm);
    $file_count = 0;
    foreach($myposts as  $mypost) :
        $files = get_children(array('post_parent' => $mypost->ID, 'post_type'  => 'attachment', 'post_mime_type'  => 'image'));
        if(is_array($files) && count($files) != 0){
            foreach($files as $file){
                $resultArray[$file_count]["url"] = wp_get_attachment_url($file->ID);
                $resultArray[$file_count]["alt"] = $file->post_title;
                $file_count++;
            }
        }
    endforeach;
     
    if(!empty($resultArray) && is_array($resultArray)){ return($resultArray); }
    else{ return(null); }
}

まずは、$catで指定されたカテゴリに属する新着記事$num件を取得します。
$numは、状況に応じて適宜調整してください。(あまり多くすると負荷が上がりますので要注意です)
なお、$numが未指定の場合は、WordPressのget_postsの初期値である5が適用されます。

取得した記事に紐付いた画像があれば取得し、配列に格納して返します。
無い場合はnullが返ります。

呼び出し方法は、以下のとおりです。

1
$imageArray = getCatImage(2,20);

該当する画像がある場合は、$imageArray[n][”url”]には画像のURLが、$imageArray[n][”alt”]には画像のタイトルが入ります。
nは数字です。

特定カテゴリに紐付いた画像を取得するにコメントする

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です