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));
}
}