HTML,CSS,PHP,ワードプレスカスタマイズ 技術情報資料

ウィジェットの作り方

テーマをカスタマイズしていると汎用的に使える機能が出てきますよね?
せっかくだから、他でも使えるようにプラグインにしてしまおう。

そのプラグインの中でも、ウィジェットは、外観のウィジェットエリアに追加して使うものです。

プラグインファイルの作成


ヘッダの作り方⇒プラグインファイルを作る

フックする場所


例えば、記事を表示直前に書き換えるならば、add_filter(‘the_content‘,’機能実現関数名’); を宣言して 機能実現関数名 という関数を作ってやればいい。

ex.
add_filter('<b>the_content</b>','wp-replace-mytag');
function wp-replace-mytag($content){ // ←送られてくる変数は、フックする場所で変わってくる
  :
  :
}

ウィジェット関数の概要


※作るウィジェットを My_Widet という名前に仮定した場合。
[FRM: r] add_action(‘widgets_init’,My_Widget_init’); // ウィジェットを登録
function My_Widget_init() {
 register_widget(‘My_Widget’);
}
class My_Widget extends WP_Widget {
 function wp_CategoryPosts() {
  $widget_ops = array(
   ’classname’ => ‘My_Widget_widget’, // クラス名 とりあえずぶつからない名前
   ’name’ => __(‘My_Widget‘), // ウィジェット選択での表示名
   ’description’ => __(‘My_Widget の説明‘) // ウィジェット選択での説明文
  );
  // Wiget Option 用 ウィンドサイズ array() とするとデフォルトサイズ
  $control_ops = array(‘width’ => 400, ‘height’ => 350);
  //—————————————————————
  // WigetID , Wiget Title(nameで指定済み) , wiget_ops , control_ops
  //—————————————————————
  parent::__construct(
   ’My_Widget_widget’, // クラス名
   __(‘Text’), // 決まり
   $widget_ops, // 表示名等
   $control_ops // ウィジェットウィンドウ属性
  );
 }
 function form($instance) {
  // ウィジェットのオプションの入力処理を記述
 }
 function update($new_instance, $old_instance) {
  // ウィジェットのオプションの保存処理を記述
 }
 function widget($args, $instance) {
  // 表示するための機能記述
 }
}
[/FRM]

ウィジェットの定義


  $widget_ops = array(
  'classname' => '<b>My_Widget</b>_widget',    // クラス名 とりあえずぶつからない名前 
  'name' => __('<b>My_Widget</b>'),          // ウィジェット選択での表示名
  'description' => __('<b>My_Widget の説明</b>')    // ウィジェット選択での説明文
 );
 // Wiget Option 用 ウィンドサイズ array() とするとデフォルトサイズ
 $control_ops = array('width' => 400, 'height' => 350);
 //---------------------------------------------------------------
 // WigetID , Wiget Title(nameで指定済み) , wiget_ops , control_ops
 //---------------------------------------------------------------
 parent::__construct(
  'My_Widget_widget',	// クラス名
  __('Text'),				// 決まり
  $widget_ops,			// 表示名等
  $control_ops			// ウィジェットウィンドウ属性
 );

ウィジェットのオプションの入力処理を記述


受け引数 $instance には、現在のオプションの値が入ってきます。

設定されている値を取り出します。
	function form($instance) {
	// ウィジェットのオプションの入力処理を記述
	if( $instance) {
		//インスタンスからオプションの値を変数に取り出す
		$title = esc_attr($instance['title']);
		$text = esc_attr($instance['text']);
	} else {
		//インスタンスが空っぽの時のオプションの初期値
		$title = '';
		$text = '';
	}
	//-----------------------------------------
	// ここから下はHTMLで表示するのでPHPを一度切る
	//-----------------------------------------
?>
	<p>
		<!-- title のラベル -->
		<label for="<?php echo $this->get_field_id('title'); ?>">
			<?php echo 'タイトル' ?>
		</label>
		<!-- title の入力 -->
		<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>"
			name="<?php echo $this->get_field_name('title'); ?>"
			type="text"
			value="<?php echo $title; ?>" ←取り出したオプションの値
		/>
	</p>

	<p>
		<!-- text のラベル -->
		<label for="<?php echo $this->get_field_id('text'); ?>">
			<?php _e('Text:'); ?>
		</label>
		<!-- text の入力 -->
		<input class="widefat" id="<?php echo $this->get_field_id('text'); ?>"
			name="<?php echo $this->get_field_name('text'); ?>"
			type="text"
			value="<?php echo $text; ?>"
		/>
	</p>
	<!---------------------------------------------------------->
	<!-- ここまでHTML、ここから下は再びphpなので php を復活させる -->
	<!---------------------------------------------------------->
<?php

ウィジェットのオプションの保存処理を記述


受け引数 $new_instance には、新しく入力されたのオプションの値、, $old_instanceには、前の値が入ってきます。
これをデータベースに保存します。$old_instance は、特に必要がなければ見なくても大丈夫。

function update($new_instance, $old_instance) {
	$instance = $old_instance;

	$instance['title'] = strip_tags($new_instance['title']);
	$instance['text'] = strip_tags($new_instance['text']);

	return $instance;
}

スポンサーリンク

表示するための機能記述


function widget($args, $instance) {
	extract( $args );
	// ウィジェットオプションの取り出し
	$title = $instance['title'];
	$text = $instance['text'];

	echo $before_widget;

	// ウィジェット本体
	echo '<div class="ウィジェット本体用のクラス">';
	// 「タイトル」の表示
	if ( $title ) {
		echo $before_title . $title . $after_title;
	}
	// 「テキスト」の表示
	if( $text ) {
		echo '<p class="cd_my_widget_text">'.$text.'</p>';
	}
	echo '</div>';

	echo $after_widget;
}

ウィジェット専用のCSSを読み込む


必要ならってことですが、CSSを読みこませるには、下のように書いて追加しておきます。。
// CSSの読み込みフック
add_action('admin_init', 'my_wedgit_css');
add_action('wp_enqueue_scripts', 'my_wedgit_css');
// CSSの設定
function my_wedgit_css() {
    echo '<link rel="stylesheet" type="text/css" href="'.plugins_url('', __FILE__).'/スタイルシートファイル名">';
}

フック場所は、以下の3つがあり好きなタイミングでフックさせます。
add_action( ‘admin_init’, ‘実行するメソッド’);//管理画面が表示される時
add_action( ‘admin_menu’, ‘実行するメソッド’);//管理画面メニューの基本構造 が表示された後
add_action( ‘wp_enqueue_scripts’, ‘実行するメソッド’);//コンテンツが表示される時

ウィジェットファイルの全景


<?php
/*
Plugin Name: プラグインの名前 (プラグインリストに表示される名前)
Plugin URI: プラグインオフィシャルのURL
 Description: プラグインの説明
Author: 作った人の名前
Author URI: 作った人のサイトURL
Version: バージョン番号
*/
//==============================================================================
// ウィジェットのフック
//------------------------------------------------------------------------------
add_action('widgets_init',My_Widget_init'); // ウィジェットを登録
function My_Widget_init() { 
    register_widget('My_Widget'); 
}
//------------------------------------------------------------------------------
// ウィジェットBODY
//------------------------------------------------------------------------------
class My_Widget extends WP_Widget {
	//==============================================================================
	// ウィジェットの定義
	//==============================================================================
	function My_Widget() {
 		$widget_ops = array(
			'classname' => 'My_Widget',    // クラス名 とりあえずぶつからない名前 
			'name' => __('My_Widget'),          // ウィジェット選択での表示名 
			'description' => __('My_Widget')    // ウィジェット選択での説明文 
		);
		// Wiget Option 用 ウィンドサイズ array() とするとデフォルトサイズ
		$control_ops = array('width' => 400, 'height' => 350);
		//---------------------------------------------------------------
		// WigetID , Wiget Title(nameで指定済み) , wiget_ops , control_ops
		//---------------------------------------------------------------
		parent::__construct(
			'My_Widget_widget',	// クラス名
			__('Text'),				// 決まり
			$widget_ops,			// 表示名等
			$control_ops			// ウィジェットウィンドウ属性
		);
	}
	//==============================================================================
	// ウィジェットのオプションの入力処理を記述
	//==============================================================================
	function form($instance) {
		if( $instance) {
			//インスタンスからオプションの値を変数に取り出す
			$title = esc_attr($instance['title']);
			$text = esc_attr($instance['text']);
		} else {
			//インスタンスが空っぽの時のオプションの初期値
			$title = '';
			$text = '';
		}
		//-----------------------------------------
		// ここから下はHTMLで表示するのでPHPを一度切る
		//-----------------------------------------
?>
	<p>
		<!-- title のラベル -->
		<label for="<?php echo $this->get_field_id('title'); ?>">
			<?php echo 'タイトル' ?>
		</label>
		<!-- title の入力 -->
		<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>"
			name="<?php echo $this->get_field_name('title'); ?>"
			type="text"
			value="<?php echo $title; ?>"
		/>
	</p>

	<p>
		<!-- text のラベル -->
		<label for="<?php echo $this->get_field_id('text'); ?>">
			<?php _e('Text:'); ?>
		</label>
		<!-- text の入力 -->
		<input class="widefat" id="<?php echo $this->get_field_id('text'); ?>"
			name="<?php echo $this->get_field_name('text'); ?>"
			type="text"
			value="<?php echo $text; ?>"
		/>
	</p>
	<!---------------------------------------------------------->
	<!-- ここまでHTML、ここから下は再びphpなので php を復活させる -->
	<!---------------------------------------------------------->
<?php
 	}
	//==============================================================================
	// ウィジェットのオプションの保存処理を記述
	//==============================================================================
	function update($new_instance, $old_instance) {
		$instance = $old_instance;

		$instance['title'] = strip_tags($new_instance['title']);
		$instance['text'] = strip_tags($new_instance['text']);

		return $instance;
 	}
	//==============================================================================
	// ウィジェット表示するための機能記述
	//==============================================================================
	function widget($args, $instance) {
		extract( $args );
		// ウィジェットオプションの取り出し
		$title = $instance['title'];
		$text = $instance['text'];

		echo $before_widget;

		// ウィジェット本体
		echo '<div class="ウィジェット本体用のクラス">';
		// 「タイトル」の表示
		if ( $title ) {
			echo $before_title . $title . $after_title;
		}
		// 「テキスト」の表示
		if( $text ) {
			echo '<p class="cd_my_widget_text">'.$text.'</p>';
		}
		echo '</div>';

		echo $after_widget;

 	}
}
//==============================================================================
// CSSの読み込みフック
//------------------------------------------------------------------------------
add_action('admin_init', 'my_wedgit_css');
add_action('wp_enqueue_scripts', 'my_wedgit_css');
//------------------------------------------------------------------------------
// CSSの設定
//------------------------------------------------------------------------------
function my_wedgit_css() {
    echo '<link rel="stylesheet" type="text/css" href="'.plugins_url('', __FILE__).'/スタイルシートファイル名">';
}
//==============================================================================

スポンサーリンク

カテゴリー