WordPress 插件开发实例 – 详细注释的 Widget 开发例子

摘要:
**@since0.1*/classExample_WidgetextendsWP_Widget{/***Widgetsetup.*/functionExample_Widget(){/*Widgetsettings.*/$widget_ops=array('classname'=˃'example','description'=˃__('Anexamplewidgetthatdisplaysaperson\'snameandsex.','example'));/*Widgetcontrolsettings.*/$control_ops=array('width'=˃300,'height'=˃350,'id_base'=˃'example-widget');/*Createthewidget.*/$this-˃WP_Widget('example-widget',__('ExampleWidget','example'),$widget_ops,$control_ops);}/***Howtodisplaythewidgetonthescreen.*/functionwidget($args,$instance){extract($args);/*Ourvariablesfromthewidgetsettings.*/$title=apply_filters('widget_title',$instance['title']);$name=$instance['name'];$sex=$instance['sex'];$show_sex=isset($instance['show_sex'])?$instance['show_sex']:false;/*Beforewidget(definedbythemes).*/echo$before_widget;/*Displaythewidgettitleifonewasinput(beforeandafterdefinedbythemes).*/if($title)echo$before_title.$title.$after_title;/*Displaynamefromwidgetsettingsifonewasinput.*/if($name)printf(''.__('Hello.Mynameis%1$s.','example').'',$name);/*Ifshowsexwasselected,displaytheuser'ssex.*/if($show_sex)printf(''.__('Iama%1$s.','example.').'',$sex);/*Afterwidget(definedbythemes).*/echo$after_widget;}/***Updatethewidgetsettings.*/functionupdate($new_instance,$old_instance){$instance=$old_instance;/*StriptagsfortitleandnametoremoveHTML(importantfortextinputs).*/$instance['title']=strip_tags($new_instance['title']);$instance['name']=strip_tags($new_instance['name']);/*Noneedtostriptagsforsexandshow_sex.*/$instance['sex']=$new_instance['sex'];$instance['show_sex']=$new_instance['show_sex'];return$instance;}/***Displaysthewidgetsettingscontrolsonthewidgetpanel.*Makeuseoftheget_field_id()andget_field_name()function*whencreatingyourformelements.Thishandlestheconfusingstuff.*/functionform($instance){/*Setupsomedefaultwidgetsettings.*/$defaults=array('title'=˃__('Example','example'),'name'=˃__('JohnDoe','example'),'sex'=˃'male','show_sex'=˃true);$instance=wp_parse_args((array)$instance,$defaults);?˃˂labelfor="get_field_id('title');?˃"˃˂?php

转自:http://summerbluet.com/225

在 wp-content\plugins 下创建 example-widget.php 代码如下 :

<?php
/**
 * Plugin Name: Example Widget
 * Plugin URI: http://example.com/widget
 * Description: A widget that serves as an example for developing more advanced widgets.
 * Version: 0.1
 * Author: Justin Tadlock
 * Author URI: http://justintadlock.com
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 */
    
/**
 * Add function to widgets_init that'll load our widget.
 * @since 0.1
 */
add_action( 'widgets_init', 'example_load_widgets' );

/**
 * Register our widget.
 * 'Example_Widget' is the widget class used below.
 *
 * @since 0.1
 */
function example_load_widgets() {
    register_widget( 'Example_Widget' );
}

/**
 * Example Widget class.
 * This class handles everything that needs to be handled with the widget:
 * the settings, form, display, and update.  Nice!
 *
 * @since 0.1
 */
class Example_Widget extends WP_Widget {

    /**
     * Widget setup.
     */
    function Example_Widget() {
        /* Widget settings. */
        $widget_ops = array( 'classname' => 'example', 'description' => __('An example widget that displays a person\'s name and sex.', 'example') );

        /* Widget control settings. */
        $control_ops = array( 'width' => 300, 'height' => 350, 'id_base' => 'example-widget' );

        /* Create the widget. */
        $this->WP_Widget( 'example-widget', __('Example Widget', 'example'), $widget_ops, $control_ops );
    }

    /**
     * How to display the widget on the screen.
     */
    function widget( $args, $instance ) {
        extract( $args );

        /* Our variables from the widget settings. */
        $title = apply_filters('widget_title', $instance['title'] );
        $name = $instance['name'];
        $sex = $instance['sex'];
        $show_sex = isset( $instance['show_sex'] ) ? $instance['show_sex'] : false;

        /* Before widget (defined by themes). */
        echo $before_widget;

        /* Display the widget title if one was input (before and after defined by themes). */
        if ( $title )
            echo $before_title . $title . $after_title;

        /* Display name from widget settings if one was input. */
        if ( $name )
            printf( '<p>' . __('Hello. My name is %1$s.', 'example') . '</p>', $name );

        /* If show sex was selected, display the user's sex. */
        if ( $show_sex )
            printf( '<p>' . __('I am a %1$s.', 'example.') . '</p>', $sex );

        /* After widget (defined by themes). */
        echo $after_widget;
    }

    /**
     * Update the widget settings.
     */
    function update( $new_instance, $old_instance ) {
        $instance = $old_instance;

        /* Strip tags for title and name to remove HTML (important for text inputs). */
        $instance['title'] = strip_tags( $new_instance['title'] );
        $instance['name'] = strip_tags( $new_instance['name'] );

        /* No need to strip tags for sex and show_sex. */
        $instance['sex'] = $new_instance['sex'];
        $instance['show_sex'] = $new_instance['show_sex'];

        return $instance;
    }

    /**
     * Displays the widget settings controls on the widget panel.
     * Make use of the get_field_id() and get_field_name() function
     * when creating your form elements. This handles the confusing stuff.
     */
    function form( $instance ) {

        /* Set up some default widget settings. */
        $defaults = array( 'title' => __('Example', 'example'), 'name' => __('John Doe', 'example'), 'sex' => 'male', 'show_sex' => true );
        $instance = wp_parse_args( (array) $instance, $defaults ); ?>

        <!-- Widget Title: Text Input -->
        <p>
            <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e('Title:', 'hybrid'); ?></label>
            <input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>"   />
        </p>

        <!-- Your Name: Text Input -->
        <p>
            <label for="<?php echo $this->get_field_id( 'name' ); ?>"><?php _e('Your Name:', 'example'); ?></label>
            <input id="<?php echo $this->get_field_id( 'name' ); ?>" name="<?php echo $this->get_field_name( 'name' ); ?>" value="<?php echo $instance['name']; ?>"   />
        </p>

        <!-- Sex: Select Box -->
        <p>
            <label for="<?php echo $this->get_field_id( 'sex' ); ?>"><?php _e('Sex:', 'example'); ?></label> 
            <select id="<?php echo $this->get_field_id( 'sex' ); ?>" name="<?php echo $this->get_field_name( 'sex' ); ?>"   style="100%;">
                <option <?php if ( 'male' == $instance['format'] ) echo 'selected="selected"'; ?>>male</option>
                <option <?php if ( 'female' == $instance['format'] ) echo 'selected="selected"'; ?>>female</option>
            </select>
        </p>

        <!-- Show Sex? Checkbox -->
        <p>
            <input   type="checkbox" <?php checked( $instance['show_sex'], true ); ?> id="<?php echo $this->get_field_id( 'show_sex' ); ?>" name="<?php echo $this->get_field_name( 'show_sex' ); ?>" /> 
            <label for="<?php echo $this->get_field_id( 'show_sex' ); ?>"><?php _e('Display sex publicly?', 'example'); ?></label>
        </p>

    <?php
    }
}

?>

免责声明:文章转载自《WordPress 插件开发实例 – 详细注释的 Widget 开发例子》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇psutil-获取系统性能信息模块Element-ui el-date-picker 时间范围只能选择1天下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

zabbix准备:php安装

一.安装php依赖库 ftp://xmlsoft.org/libxml2/libxml2-2.9.3.tar.gz yum install python-devel -y cd /download/ wget -c ftp://xmlsoft.org/libxml2/libxml2-2.9.3.tar.gz tar xf libxml2-2.9.3...

[GXYCTF2019]BabysqliV3.0题解

[GXYCTF2019]BabysqliV3.0 常规分析 题目叫babysqli,刚访问的时候会有一个登录页面,于是我用测了测sql注入,毫无收获。 最后发现是弱口令,账号admin,密码password。 登录进去以后是这样的: url末尾是file=的形式,怀疑是文件包含,并且自动在xxx后面加.php。 将file=后面的参数改为php://fi...

CentOS 7编译安装Tengine+PHP+MariaDB全程笔记

  安装环境:CentOS7 3.10.0-693.5.2.el7.x86_64   准备源码包:     pcre-8.41.tar.gz     openssl-1.0.1h.tar.gz     zlib-1.2.11.tar.gz     jemalloc-4.5.0.tar.bz2     tengine-2.1.0.tar.gz     lib...

22个开源的PHP框架

copy from: http://coolshell.cn/articles/1086.html PHP 是一个被广泛使用的来进行Web开发的脚本语言。虽然有很多其它可供选择的Web开发语言,像:ASP 和Ruby,但是PHP是目前为止世界上最为流行的。 那么,是什么让PHP如此流行?PHP 如此之流行是因为比起别的语言来,它更容易学习,网上有一大堆相当...

Linux的PHP开发环境快速搭建

搭建的环境是LNMP: 1、安装MySQL 这个非常简单我用的是Ubuntu那么就用apt源,下载deb文件然后按照全新安装文档按顺序:a.加入apt库  b.更新apt库 c.安装 d.运行MySQL 下载: https://dev.mysql.com/downloads/repo/apt/ 文档: https://dev.mysql.com/doc/m...

php中对象转换数组与数组转换对象实例

用stdClass转换数组为对象                                                                                  Php代码 $arr = array(); $arr['a'] = 1;...