オリジナルのウィジットを作成する機会があったので、メモ。
(参考サイト)
WordPress 2.8登場!新ウィジェットAPIの使い方
WordPress 2.8でウィジェット作成(1) – Hello World
今回は独自に作成したテーマにカスタム投稿した内容をリスト表示するウィジットを作成してみました。
まず、クラスを定義します。
できるだけソースを見やすくしたかったので、テーマフォルダ内にwidgetsというフォルダを作成し、その中にオリジナルのウィジットソースを保存しました。
今回はOriginal_info.phpという名前でphpファイルを作成しています。※ファイル名は任意。
(テーマフォルダ)\widgets\Original_info.php
<?php
class Original_info extends WP_Widget {
// コンストラクタ
function Original_info() {
$widget_ops = array('classname' => 'Original_info', 'description' => 'オリジナルで作成したウィジェットです。' );
parent::WP_Widget(false, $name = 'オリジナルテーマ', $widget_ops);
}
// widgetメソッドの定義
function widget($args, $instance) {
extract( $args );
// タイトルを設定
$title = $instance['title'] == '' ? 'インフォメーション' : $instance['title'];
$post_type = $instance['post_type'] == '' ? 'info' : $instance['post_type'];
?>
<?php echo $before_widget; ?>
<?php echo $before_title
. wp_specialchars($title)
. $after_title; ?>
<?php
// カスタム投稿内容の表示
$infolist = new wp_query( array('post_type'=>$post_type, 'post_status'=>'publish', 'posts_per_page'=>3, 'order'=>'DESC', 'orderby'=>'date') );
if ($infolist->have_posts()) :
?>
<ul class="widget_body original_info_body">
<?php
while ($infolist->have_posts()) {
$infolist->the_post();
$list = "<li>";
$list .= "<div class=\"title\">" . get_the_title() . "</div>";
$list .= "<p>" . get_the_excerpt() . "</p>";
$list .= "</li>\n";
echo $list;
}
?>
</ul>
<?php endif; wp_reset_query(); ?>
<?php echo $after_widget; ?>
<?php
}
// 保存したときの処理
function update($new_instance, $old_instance) {
return $new_instance;
}
// 管理画面のウィジェットに設定項目追加
function form($instance) {
$title = $instance['title'] == '' ? 'インフォメーション' : esc_attr($instance['title']);
$post_type = $instance['post_type'] == '' ? 'info' : esc_attr($instance['post_type']);
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>">タイトル:
<input id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
</label>
<label for="<?php echo $this->get_field_id('post_type'); ?>">PostType:
<input id="<?php echo $this->get_field_id('post_type'); ?>" name="<?php echo $this->get_field_name('post_type'); ?>" type="text" value="<?php echo $post_type; ?>" />
</label>
</p>
<?php
}
}
?>
次にfunctions.phpにてwidgets_initアクションで作成したウィジェットを登録するコードを追加する。
if (version_compare($wp_version, '2.8', '>=')){
require_once(TEMPLATEPATH . "/widgets/original_info.php");
add_action( 'widgets_init', create_function('', 'return register_widget("Original_info");'));
}
ここまで作成すると管理画面のウィジェットで下記のように追加されます。
※上記例ではウィジェットエリア1に今回作成したオリジナルのウィジェットを2つ追加し、1つはpost_type:infoのカスタム投稿、もう1つはpost_type:newsのカスタム投稿を表示しています。
