Standing on the Shoulder of Linus

Home / 2012 / 1月 / 21 / PHPTAL で WordPress カスタムフィールド

PHPTAL で WordPress カスタムフィールド

PHPTAL テンプレートエンジンを使う場合、WordPress カスタムフィールドは結構面倒です。WordPress 標準の $posts には、カスタムフィールド情報は含まれていません。

tal:content="php:get_post_meta(ID,フィールド名,true) みたいに書く方法もあるのですが、これだとテンプレートファイルが汚くなるように思います。

なので、PHP 側でカスタムフィールドも含めた配列を作っておくことにします(テンプレート側は呼び出し用にキーを書くだけ)。

<?php
/* index.php */
$template = new PHPTAL(TEMPLATEPATH . '/index.html');
$myposts = array();
while( have_posts() ) : the_post();
	$myarr = array(
	'ID' => get_the_ID(),
	'title' => get_the_title(),
	'post_content' => apply_filters('the_content', get_the_content()),
	'permalink' => get_permalink(),
	'post_modified' => get_the_modified_date(),
);
$custom = get_post_custom();
foreach ($custom as $key => $val) {
$myarr['custom'.$key] = arr_to_str($val); // arr_to_str は配列だったらimplodeする自作関数
}
$myposts[] = $myarr;
endwhile;
$template->items = $myposts;
<div tal:content="item/custommykey | default">デフォルトの値</div>

テンプレート側では、mykey というキーのカスタムフィールドを表示します(プレフィックスcustomは他とかぶらない用に設定しています)。| defaultという記述で、存在し無かった場合にデフォルト値を表示するようにしています(詳細はPHPTALのXHTML参照)。値が無い場合の処理もテンプレート側で行えるのは、地味に便利だったりします。

$myarr['custom'.$key] の部分は、$myarr['custom'][$key] のほうがいいかもしれません。

※PHPTAL はオープンソースで公開されています。貢献されている皆様に感謝します。

おまけ arr_to_str 関数

function arr_to_str($arr) {
	if ( is_array($arr) ) {
	return implode(',',$arr);
	} elseif (is_string($arr) || is_int($arr) || is_float($arr) ) {
	return strval($arr);
	} else {
		return false;
	}
}

phpunit を使ったユニットテスト

class myfuncTest extends PHPUnit_Framework_testCase {
	public function testArrayString() {
		$data = array('abc');
		$this->assertEquals('abc',arr_to_str($data));
	}
	public function testString() {
		$data = 'abc';
		$this->assertEquals('abc',arr_to_str($data));
	}
	public function testIntString() {
		$data = 55;
		$this->assertEquals('55',arr_to_str($data));
	}
	public function testFloatString() {
		$data = 5.5;
		$this->assertEquals('5.5',arr_to_str($data));
	}
	public function testEmptyString() {
		$data = '';
		$this->assertEquals('',arr_to_str($data));
	}
	public function testNull() {
		$data = NULL;
		$this->assertEquals(false,arr_to_str($data));
	}
}

関連

Posted in WordPress | Tagged xhtml, テンプレート
← sahana eden を Ubuntu 11.10 で動かす ページ毎のウィジェット表示非表示をfunctions.phpで制御する方法 →

アーカイブ

人気の投稿とページ

  • キンドル本を印刷する(PDFに変換する)方法
  • 名古屋駅から国際センターまでの道のり(徒歩)
  • AGPL ライセンス(GPLとは似ているが違いもある)
  • 6年使ったイーモバイル(Y!mobile)を解約手続。店頭でSIM返却
  • JP-Secure SiteGuard WP Pluginは不正ログイン防止に役立つか

プロフィール

水野史土:月70万PVホームページ制作会社のレスキューワーク株式会社で、PHPソフトウェアのサポートを行っている。concrete5コミュニティリーダー、Novius OSコアコード貢献者でもある。 詳しくは管理者詳細参照。
大好評WordPress書籍「WordPressユーザーのためのPHP入門 はじめから、ていねいに。」サポートページ

Copyright © 2015 Standing on the Shoulder of Linus.