03自訂模組(widget)

Screen Shot 2016-01-14 at 6.04.44 PM

Screen Shot 2016-01-14 at 6.03.54 PM

程式參考來源: 這裡

程式下載: 這裡

[php]
<?php

/*
Plugin Name: PowenKo Page POST Meta
Plugin URI: http://wordpress.org/plugins/hello-dolly/
Description: This is not just a plugin, it symbolizes the hope and enthusiasm of an entire generation summed up in two words sung most famously by Louis Armstrong: Hello, Dolly. When activated you will randomly see a lyric from <cite>Hello, Dolly</cite> in the upper right of your admin screen on every page.
Author: Powen Ko
Version: 1.6
Author URI: http://ma.tt/
*/
// 註冊自訂的Widget-EX_Widget
function register_ex_widget() {
register_widget( 'EX_Widget' );
}
add_action( 'widgets_init', 'register_ex_widget' );

// 自訂的EX_Widget類別,要繼承WP_Widget
class EX_Widget extends WP_Widget {
// 一些初始化設定
function EX_Widget() {
$widget_ops = array( 'classname' => 'side_ex', 'description' => '還記得我嗎?大聲點我聽不見~');
$control_ops = array( 'width' => 300, 'height' => 750, 'id_base' => 'side_ex-widget' );
$this->WP_Widget( 'side_ex-widget', '我的名字', $widget_ops, $control_ops );
}

// 描述widget顯示於前台時的外觀
function widget( $args, $instance ) {
// $args裡可以拿到所在版位的相關資訊,如before_widget、after_widget..等
extract( $args );
echo $before_widget;
$myname = $instance['myname'];
echo "<h2>$myname</h2>";
echo $after_widget;
}

// 於後台更新Widget時會做的事
function update( $new_instance, $old_instance ) {
$instance = $old_instance;
// 簡單幫設定內容作一下Strip tags,擋掉html tag
$instance['myname'] = strip_tags( $new_instance['myname'] );
return $instance;
}

// Widget在後台模組頁的外觀
function form( $instance ) {
// 可以設定預設值
$defaults = array('myname'=>'熱血大叔');
$instance = wp_parse_args( (array) $instance, $defaults ); ?>
<p>
<label for="<?php echo $this->get_field_id( 'myname' ); ?>">設定要顯示的名字:</label>
<input type="text" name="<?php echo $this->get_field_name( 'myname' ); ?>" value="<?php echo $instance['myname']; ?>">
</p>
<?php
}
}
/////////////////////////
function side_widgets_init() {
register_sidebar(array(
'name' => '側欄模組區',
'id' => 'sidebar-sec',
'before_widget' => '<div id="%1$s" class="%2$s sidebar_frm">',
'after_widget' => '</div>',
'before_title' => '<h4 class="widgettitle">',
'after_title' => '</h4>',
));
}
add_action( 'widgets_init', 'side_widgets_init' );
/////////

if ( !function_exists('dynamic_sidebar')|| !dynamic_sidebar('sidebar-sec') ){
// 如果wp版本不支援顯示或者找不到你所設定的模組ID,就會執行這個區塊裡的程式...blah blah...
}

?>

[/php]

wordpress
CH02用戶資料CH03基本APICH05 分類頁面Category.phpCH09Screen Options(顯示選項)CH10外掛pluginsCH11 add_actionCH12 add_filterCH13Meta Box(自訂區塊)CH14widget(自訂模組)CH15 DBCH16AJAXCH17ShortcodeCH20 wordpress muCH30WooCommerce