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

WP プラグイン構造の作り方

MyPlugin というプラグインを作る場合を想定。

PLUGIN 本体 ファイル

 
MyPlugin.php
<?php
/*
Plugin Name: MyPlugin
Plugin URI: http://my domain/
Description: Plugin document
Version: 1.4.11
Author: author name.
Author URI: http://my domain/
*/
/*==============================================================================*/
/* define list */
/*==============================================================================*/
/* version */
define('MYPLUGIN_VERSION', '1.4.11.1411061');
/* path */
define('MYPLUGIN_WP_CONTENT_DIR', ABSPATH    . 'wp-content');
define('MYPLUGIN_WP_CONTENT_URL', site_url() . '/wp-content');
define('MYPLUGIN_WP_PLUGIN_DIR' , MYPLUGIN_WP_CONTENT_DIR . '/plugins');
define('MYPLUGIN_WP_PLUGIN_URL' , MYPLUGIN_WP_CONTENT_URL . '/plugins');
$WP_MyPlugin_fld = str_replace(basename(__FILE__),"",plugin_basename(__FILE__));
$WP_MyPlugin_URL = WP_PLUGIN_URL.'/'.$WP_MyPlugin_fld;	// 最後 / で終わってる
$WP_MyPlugin_DIR = WP_PLUGIN_DIR.'/'.$WP_MyPlugin_fld;	// 最後 / で終わってる
/*==============================================================================*/
/* global simbol */
/*==============================================================================*/
global $MyPlugin_settings, $MyPlugin_states;
/*==============================================================================*/
/* function include */
/*==============================================================================*/
/* initial */
require_once(MYPLUGIN_PLUGIN_DIR."/includes/initial.php");
require_once(MYPLUGIN_PLUGIN_DIR."/includes/css_inport.php");
/* class */
require_once(MYPLUGIN_PLUGIN_DIR."/classes/widgets.class.php");
/* filter */
require_once(MYPLUGIN_PLUGIN_DIR."/functions/filters.php");
/* addmin only */
if( is_admin() ){
	require_once(MYPLUGIN_PLUGIN_DIR."/functions/admin_page.php");
}
?>
そうするとメインファイルはスッキリする。
 

設定画面

 
initial.php
/*=============================================================*/
/* Welcart 設定 管理画面 書式設定関数 フック設定 */
/*=============================================================*/
add_action('admin_menu','MyPlugin_menu');
function MyPlugin_menu() {
	add_options_page(
		'MyPlugin Option',			/* 1.ページの題名(My Plugin Options) */
		'MyPlugin Name',			/* 2.adminメニューでのページ名(My Plugin) */
		'administrator',			/* 3.アクセスレベル */
		'MyPlugin',					/* 4.(URLに入る名前)  モジュールが1つなら '__FILE__' でOK */
		'MyPlugin_menu_setting'		/* 5.管理パネルの中身関数 */
	);

        :
    必要な管理画面分書く
        :

}
//------------------------------------------------------------------------------
function MyPlugin_menu_setting()
//------------------------------------------------------------------------------
{
	//--------------------------------------------------------------------------
	// 準備
	//--------------------------------------------------------------------------
        :
		
	//--------------------------------------------------------------------------
	// put
	//--------------------------------------------------------------------------
	if (isset($_POST['update_option'])) {
		$target = $_POST["target"]; // $_POST の中に入ってる欲しいフィールを拾う 
		// ここから下は、味噌ね? テキストエリアでデータを拾う場合
		$target = str_replace('<','&lt;'   ,$target);
		$target = str_replace('>','&gt;'   ,$target);
		$target = str_replace('"','&quot;' ,$target);
		// ---- ここまで。一括で置き換えするのが正解だけどわかりやすくするため1つづつにしました

		$value = $_POST['value'];
        		:
		// 拾ったデータをDBに書きだす
		update_option('MyPlugin_target'  ,$target);
		update_option('MyPlugin_value'   ,$value);
        		:
	}
	//--------------------------------------------------------------------------
	// get
	//--------------------------------------------------------------------------
	// DB に書きだされているデータを取り出す
	$value = get_option('MyPlugin_value');
	$target = get_option('MyPlugin_target');
	// 味噌その2
	$target = str_replace('\&quot;','&quot;',$target);
	// ---- ここまで。&quot; が自動的に \&quot; に置き換えられるので、ここで変換しておく
        :

	//--------------------------------------------------------------------------
	// 表示前準備
	//--------------------------------------------------------------------------
        :

	//--------------------------------------------------------------------------
	// 表示
	//--------------------------------------------------------------------------

	echo <<<EOD
	<form name="form" method="post" action="">

		<input type="text" name="value" value="$value" size="4">
		<textarea name="target" cols="20" rows="3">$target</textarea>
		<input type='submit' name='update_option' class='buttonprimary'>
	</form>
	
EOD;
}
 

ウィジェットクラス

 
widgets.class.php
//==============================================================================
// ウイジェットクラス
//==============================================================================
add_action('widgets_init', 'WP_MyPlugin_WidetInit');
function WP_MyPlugin_WidetInit() {
	
	require_once($pdir."MyPlugin_Widet1.php");
	register_widget('MyPlugin_Widet1');
	
	require_once($pdir."MyPlugin_Widet2.php");
	register_widget('MyPlugin_Widet2');

                :
        必要な分だけ書く
                :
}
 
MyPlugin_Widet2.php
//==============================================================================
class MyPlugin_Widet2 extends WP_Widget
//==============================================================================
{
	//--------------------------------------------------------------------------
	// 定義
	//--------------------------------------------------------------------------
	function MyPlugin_Widet2() {
		$widget_ops = array(
			// クラス名
			'classname' => 'MyPlugin_Widet2',
			// ウィジェットのボックスに表示される名前
			'name' => __('MyPlugin Box Widet'),
			// ウィジェットのボックスに表示される説明
			'description' => __('This is MyPlugin box widet.')
		);
		// Wiget Option 用 ウィンドサイズ array() とするとデフォルトサイズ
		$control_ops = array('width' => 400, 'height' => 350);
		// WigetID , Wiget Title(nameで指定済み) , wiget_ops , control_ops
		parent::__construct('WelcartMyBox_widget', __('Text'), $widget_ops, $control_ops);
	}
	//--------------------------------------------------------------------------
	// 表示実際の表示
	//--------------------------------------------------------------------------
	function widget($args, $instance) {
		extract($args);
		// get Widet Box の設定でエントリーされたもの 
		$title = apply_filters( 'widget_title' , empty( $instance['title']  ) ? '' : $instance['title'] , $instance, $this->id_base );
		$text  = apply_filters( 'widget_text'  , empty( $instance['text']   ) ? '' : $instance['text']  , $instance );
		$templ = apply_filters( 'widget_templ' , empty( $instance['templ']  ) ? '' : $instance['templ'] , $instance );
		// 表示ブロック(タイトルにタグはいれさせない処理)
		echo $before_widget;
		if ( !empty( $title ) ) { echo $before_title . $title . $after_title; } ?>
			<div class="textwidget"><?php echo !empty( $instance['filter'] ) ? wpautop( $text ) : $text; ?></div>
		<?php
		echo MyPluginBox_View($text,$templ);	// 実際のブロック作成は、でかくなるので別モジュール
		echo $after_widget;
	}
	//--------------------------------------------------------------------------
	// 設定値の書き込み
	//--------------------------------------------------------------------------
	function update($new_instance, $old_instance) {
		// processes widget options to be saved
		$instance = $old_instance;
		$instance['title']  = strip_tags($new_instance['title']);
		if ( current_user_can('unfiltered_html') ){
			$instance['text'] =  $new_instance['text'];
		}else{
			// wp_filter_post_kses() expects slashed
			$instance['text'] = stripslashes( wp_filter_post_kses( addslashes($new_instance['text']) ) ); 
		}
		$instance['templ']  = $new_instance['templ'];
		return $instance;
	}
	//--------------------------------------------------------------------------
	//設定(ウィジェットをサイドバーに乗せたときの各種値)入力フォーム
	//--------------------------------------------------------------------------
	function form($instance) {
		//----------------------------------------------------------------------
		// get  設定値を取り込む
		//----------------------------------------------------------------------
		$instance = wp_parse_args( (array) $instance,
			array( 'title'  => '',
					'text'  => '',
					'templ' => ''
			));
		$title = strip_tags( $instance[ 'title']);
		$text  = esc_textarea($instance['text']);
		$templ = strip_tags( $instance[ 'templ']);
		//----------------------------------------------------------------------
		// 設定値のエントリーフォーム
		//----------------------------------------------------------------------
?>
		<p><label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label>
		<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" /></p>

		<p><label for="<?php echo $this->get_field_id('text'); ?>"><?php _e('表示前コメント:'); ?></label>
		<textarea class="widefat" rows="2" cols="20" id="<?php echo $this->get_field_id('text'); ?>" name="<?php echo $this->get_field_name('text'); ?>"><?php echo $text; ?></textarea></p>
		
		<p><input id="<?php echo $this->get_field_id('filter'); ?>" name="<?php echo $this->get_field_name('filter'); ?>" type="checkbox" <?php checked(isset($instance['filter']) ? $instance['filter'] : 0); ?> />&nbsp;<label for="<?php echo $this->get_field_id('filter'); ?>"><?php _e('Automatically add paragraphs'); ?></label></p>

		<p><label for="<?php echo $this->get_field_id('templ'); ?>"><?php _e('テンプレート:'); ?></label>
		<textarea class="widefat" rows="2" cols="20" id="<?php echo $this->get_field_id('templ'); ?>" name="<?php echo $this->get_field_name('templ'); ?>"><?php echo $templ; ?></textarea></p>

<?php
	}
}
//==============================================================================
function MyPluginBox_View()
//==============================================================================
{
        :
	return($display_line_block);	// 実際に表示するものを返してやる
}
 

CSSの取り込み

 
css_inport.php
//******************************************************************************
// CSS の追加
//******************************************************************************
//==============================================================================
// 表示用CSS追加
//==============================================================================
add_action( 'wp_print_styles', 'MyPlugin_styles', 100 );
function MyPlugin_styles() {
	/* 専用CSSを読み込ませる */
	$plugin_dir = str_replace(basename(__FILE__),"",plugin_basename(__FILE__));
	$css_url = WP_PLUGIN_URL.'/'.$plugin_dir.'css/MyPlugin.css';
	// link tag ID , css url , false , '1' 
	wp_enqueue_style( 'MyPlugin_styles', $css_url, false, '1' );
}
//==============================================================================
// 専用管理画面用CSS追加
//==============================================================================
add_action('admin_init', 'MyPlugin_add_init');
function MyPlugin_add_init(){
	wp_register_style('MyPlugin', plugins_url('css/MyPlugin_admin.css', __FILE__));
	wp_enqueue_style( 'MyPlugin');
}
 

ウィジェットエリアの作成

 
これは、テーマ側で処理すべきことだけど書いておく。
ウィジェット領域に 「インフォメーション」というエリアを作る場合。
テーマの function.php (自分でテーマを作るのでなければ、(A)~(/A)の部分をコピーして貼り付けてやればいい)
<?php
//----- ここから ---
// ↓これは別の処理でヘッダー画像交換の処理用、この話には関係ないので、何か書いてあるって意味。
$args = array(
	'width'         => 1020,
	'height'        => 300,
	'default-image' => get_template_directory_uri() . '/img/header.jpg',
	'uploads'       => true,
);
add_theme_support( 'custom-header', $args );
//----- ここまで ---

//----- ここからが大事な?
if ( function_exists('register_sidebar') ) {
    //------ (A) -----
    register_sidebar(array(
        'name' =>'インフォメーション',
        'before_widget' => '<section class="info">',
        'after_widget' => '</section>',
        'before_title' => '<h2 class="main-title">',
        'after_title' => '</h2>',
    ));
    //------ (/A) -----
     :
  必要な分だけ書いてやる
     :
}
//---------------------------
 
実際の表示場所は、テーマのファイルの中の表示させるべきところに以下のように埋め込む。

<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('インフォメーション') ) : ?>
<?php endif; ?>

スポンサーリンク

関連記事

スポンサーリンク

カテゴリー