KennyQi PHP Blog

Linux、PHP、Perl、Ajax、MySQLでのWeb開発やWordPressの設定メモと息抜きブログ

  • 6月132011

    WordPressで記事内の画像を取得

    Published on 2011/06/13 17:35 1,045
    カテゴリ: CMS, WordPress; タグ:

    WordPressは、記事本文以外に
    「アイキャッチ画像」として画像を登録していれば
    テンプレ内などで画像を取得する関数(WordPressのテンプレートタグ)を用意しています。

    Codex テンプレートタグ/the post thumbnail

    が、アイキャッチ画像ではなく、
    記事本文内にある画像を取得したい場合は、どうやら無さそうなので
    「テンプレートタグ」を自作しました。メモしておきます。

    下記のコードをテーマ内のfunction.phpに記述すれば、テーマ内で呼び出せます。

    <?php get_the_content_image() ?>

    いわゆるループ内で呼び出すタグです。
    while ( have_posts() )

    endwhile;
    の間で呼び出すとそれぞれの記事から画像を取ってきます。
    引数なし、返り値は画像URLです。

    	// 記事内の画像を取ってくる
    	function get_the_content_image() {
    		 global $post, $posts;
    		 $first_img = '';
    		 ob_start();
    		 ob_end_clean();
    		 $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
    		 $first_img = $matches [1] [0];
    
    		 if(empty($first_img)){ //Defines a default image
    			 $first_img = "/no-image.gif";
    		 }
    		 return $first_img;
    	}
    

    <?php get_the_contetn_image_by_postID($postid) ?>

    ループ外で呼び出すタグです。
    引数は記事ID(半角数字)、返り値は画像URLです。

    	// 記事ID指定
    	function get_the_contetn_image_by_postID($postid) {
    		 $post=get_post($postid);
    		 $first_img = '';
    		 ob_start();
    		 ob_end_clean();
    		 $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
    		 $first_img = $matches [1] [0];
    
    		 if(empty($first_img)){ //Defines a default image
    		 $first_img = "/no-image.gif";
    		 }
    		 return $first_img;
    	}
    
    このページはどうでしたか?
    よくないよい (No Ratings Yet)
    No Comments
  • 初めて当ブログに訪れた方や何度か当ブログにお越し頂いている皆様。
    もしブログの内容を気に入って頂けましたらRSSリーダーの登録よろしくお願いします。

コメント


ブログランキング

にほんブログ村 IT技術ブログへ 人気ブログランキングへ

最新記事

カテゴリー

人気記事