外贸独立站的底层设计密码WordPress 成品站模板
当前位置:首页>WordPress建站>WordPress开发>如何使用 WordPress 的拾色器(Color Picker)API

如何使用 WordPress 的拾色器(Color Picker)API

在一些 WordPress 主题或插件项目中,我们经常要用到拾色器,今天我们就一起来看看如何使用 WordPress 的拾色器(Color Picker)API。在开始前,请确保你的 WordPress 是 3.5 以及以上版本,这样才能适用本教程。

引用拾色器文件

要添加拾色器,我们需要引用它的jQuery和CSS样式文件。下面的代码将告诉你怎么引用:

add_action( 'admin_enqueue_scripts', 'wptuts_add_color_picker' );
function wptuts_add_color_picker( $hook ) {
 
    if( is_admin() ) { 
     
        // 添加拾色器的CSS文件       
        wp_enqueue_style( 'wp-color-picker' ); 
         
        // 引用我们自定义的jQuery文件以及加入拾色器的支持
        wp_enqueue_script( 'custom-script-handle', plugins_url( 'custom-script.js', __FILE__ ), array( 'wp-color-picker' ), false, true ); 
    }
}

请注意,当我们引用了自定义的jQuery文件以及加入拾色器的支持后,我们就可以将拾色器应用到jQuery文件中的文本字段。

(function( $ ) {
 
    // 添加颜色选择器到所有包含"color-field"类的 input 中
    $(function() {
        $('.color-field').wpColorPicker();
    });
     
})( jQuery );

创建一个使用拾色器的插件

下面我们就来展示如何整合拾色器到一个真正的插件里面。

以下就是我们要讲解的:

  • 如何添加一个仪表盘选项页面,模拟一个主题设置页面。
  • 如何添加准备使用拾色器的设置字段。
  • 如何验证并保存输入。

步骤1

一旦你设置了你的插件到 WordPress 的 wp-content/plugins 文件夹里面,我们就已经做好了开始的准备。下图显示了我如何结构化本教程所做的插件。

color-picker-api_wpdaxue_com

步骤2

color-picker-plugin.php 文件里面,我们填写了插件的基本信息,然后创建一个名为 CPA_Theme_Options 的PHP类,下面的代码显示了我们将要实现一步一步的所有类方法。

/*
Plugin Name: Color Picker API
Plugin URI: http://code.tutsplus.com
Description: Demo about the new Color Picker API
Version: 1.0
Author: code.tutsplus.com
Author URI: http://code.tutsplus.com
*/
 
/**
 * Main Class - CPA stands for Color Picker API
 */
class CPA_Theme_Options {
  
    /*--------------------------------------------*
     * Attributes
     *--------------------------------------------*/
  
    /** Refers to a single instance of this class. */
    private static $instance = null;
     
    /* Saved options */
    public $options;
  
    /*--------------------------------------------*
     * Constructor
     *--------------------------------------------*/
  
    /**
     * Creates or returns an instance of this class.
     *
     * @return  CPA_Theme_Options A single instance of this class.
     */
    public static function get_instance() {
  
        if ( null == self::$instance ) {
            self::$instance = new self;
        }
  
        return self::$instance;
  
    } // end get_instance;
  
    /**
     * Initializes the plugin by setting localization, filters, and administration functions.
     */
    private function __construct() { }
  
    /*--------------------------------------------*
     * Functions
     *--------------------------------------------*/
      
    /**
     * Function that will add the options page under Setting Menu.
     */
    public function add_page() { }
      
    /**
     * Function that will display the options page.
     */
    public function display_page() { }
       
    /**
     * Function that will register admin page options.
     */
    public function register_page_options() { }
     
    /**
     * Function that will add javascript file for Color Piker.
     */
    public function enqueue_admin_js() { }
     
    /**
     * Function that will validate all fields.
     */
    public function validate_options( $fields ) { }
     
    /**
     * Function that will check if value is a valid HEX color.
     */
    public function check_color( $value ) { }
     
    /**
     * Callback function for settings section
     */
    public function display_section() { /* Leave blank */ } 
     
    /**
     * Functions that display the fields.
     */
    public function title_settings_field() { }   
     
    public function bg_settings_field( ) { }
         
} // end class
  
CPA_Theme_Options::get_instance();

步骤3

首先,让我们来实现类的构造函数。下面的代码显示了一个新的实例将被创建时,这个插件就行了。

它将:

  • 在WordPress管理菜单的设置部分添加一个新的选项页
  • 注册选项页面中注册设置字段
  • 添加 WordPress 拾色器的CSS样式表
  • 添加调用拾色器的自定义 JavaScript 文件
  • 设置选项属性与保存设置。
private function __construct() { 
 
    // Add the page to the admin menu
    add_action( 'admin_menu', array( &$this, 'add_page' ) );
     
    // Register page options
    add_action( 'admin_init', array( &$this, 'register_page_options') );
     
    // Css rules for Color Picker
    wp_enqueue_style( 'wp-color-picker' );
     
    // Register javascript
    add_action('admin_enqueue_scripts', array( $this, 'enqueue_admin_js' ) );
     
    // Get registered option
    $this->options = get_option( 'cpa_settings_options' );
}

步骤4

接下来的步骤介绍如何添加选项页,以及如何显示它。

/**
 * Function that will add the options page under Setting Menu.
 */
public function add_page() { 
     
    // $page_title, $menu_title, $capability, $menu_slug, $callback_function
    add_options_page( 'Theme Options', 'Theme Options', 'manage_options', __FILE__, array( $this, 'display_page' ) );
}
 
/**
 * Function that will display the options page.
 */
public function display_page() { 
    ?>
    <div class="wrap">
     
        <h2>Theme Options</h2>
        <form method="post" action="options.php">     
        <?php 
            settings_fields(__FILE__);      
            do_settings_sections(__FILE__);
            submit_button();
        ?>
        </form>
    </div> <!-- /wrap -->
    <?php    
}

请注意,我们已经写了 —— 在 display_page() 函数里 —— 将添加表单、字段和提交按钮用于注册页面选项的代码。

步骤5

在这一步中,我们要实现注册并显示两个字段的设置方法:博客标题字段和背景颜色字段。这两个领域都属于主题选项部分。

/**
 * Function that will register admin page options.
 */
public function register_page_options() { 
     
    // Add Section for option fields
    add_settings_section( 'cpa_section', 'Theme Options', array( $this, 'display_section' ), __FILE__ ); // id, title, display cb, page
     
    // Add Title Field
    add_settings_field( 'cpa_title_field', 'Blog Title', array( $this, 'title_settings_field' ), __FILE__, 'cpa_section' ); // id, title, display cb, page, section
     
    // Add Background Color Field
    add_settings_field( 'cpa_bg_field', 'Background Color', array( $this, 'bg_settings_field' ), __FILE__, 'cpa_section' ); // id, title, display cb, page, section
     
    // Register Settings
    register_setting( __FILE__, 'cpa_settings_options', array( $this, 'validate_options' ) ); // option group, option name, sanitize cb 
}
 
/**
 * Functions that display the fields.
 */
public function title_settings_field() { 
     
    $val = ( isset( $this->options['title'] ) ) ? $this->options['title'] : '';
    echo '<input type="text" name="cpa_settings_options[title]" value="' . $val . '" />';
}   
 
public function bg_settings_field() { 
     
    $val = ( isset( $this->options['title'] ) ) ? $this->options['background'] : '';
    echo '<input type="text" name="cpa_settings_options[background]" value="' . $val . '" class="cpa-color-picker" >';
     
}

步骤6

这个步骤的重点是验证。下面的代码显示了如何在保存它们之前验证这两个领域。

/**
 * Function that will validate all fields.
 */
public function validate_options( $fields ) { 
     
    $valid_fields = array();
     
    // Validate Title Field
    $title = trim( $fields['title'] );
    $valid_fields['title'] = strip_tags( stripslashes( $title ) );
     
    // Validate Background Color
    $background = trim( $fields['background'] );
    $background = strip_tags( stripslashes( $background ) );
     
    // Check if is a valid hex color
    if( FALSE === $this->check_color( $background ) ) {
     
        // Set the error message
        add_settings_error( 'cpa_settings_options', 'cpa_bg_error', 'Insert a valid color for Background', 'error' ); // $setting, $code, $message, $type
         
        // Get the previous valid value
        $valid_fields['background'] = $this->options['background'];
     
    } else {
     
        $valid_fields['background'] = $background;  
     
    }
     
    return apply_filters( 'validate_options', $valid_fields, $fields);
}
 
/**
 * Function that will check if value is a valid HEX color.
 */
public function check_color( $value ) { 
     
    if ( preg_match( '/^#[a-f0-9]{6}$/i', $value ) ) { // if user insert a HEX color with #     
        return true;
    }
     
    return false;
}

如果用户试图手动插入的颜色代码,拾色器通知他或她,他/她已经键入的提交表单上的无效值;然而,颜色—— 尽管它可能是错误的——仍然会被保存。该check_color() 函数负责验证输入的颜色。

步骤7

这是最后一步,我们将要引用我们自定义的 JavaScript 文件,用来在拾色器中转换一个简单的文本字段。

/**
 * Function that will add javascript file for Color Piker.
 */
public function enqueue_admin_js() { 
     
    // Make sure to add the wp-color-picker dependecy to js file
    wp_enqueue_script( 'cpa_custom_js', plugins_url( 'jquery.custom.js', __FILE__ ), array( 'jquery', 'wp-color-picker' ), '', true  );
}

让我们创建 jquery.custom.js 文件

(function( $ ) {
    $(function() {
         
        // Add Color Picker to all inputs that have 'color-field' class
        $( '.cpa-color-picker' ).wpColorPicker();
         
    });
})( jQuery );

如果您尝试激活该插件,你应该得到一个仪表板页面,如下所示的图像中的所有字段:

color-picker-api-2_wpdaxue_com

小结

在本教程中,您学习了如何以引用WordPress拾色器。在插件演示中,我已经展示了如何整合拾色器到一个真正的插件,当然,你可以在 meta框、窗口小部件等等中使用这个 API。

拾色器可以在 WordPress3.5+ 中正常工作,但如果用户有以前版本,代码也将工作。请务必使用 check_color() 方法来验证每一种颜色输入(步骤6所示)。

现在,你的插件或主题将是更强大的和更友好。

参考资料:http://code.tutsplus.com/articles/how-to-use-wordpress-color-picker-api–wp-33067

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

给TA打赏
共{{data.count}}人
人已打赏
欢迎关注WordPress大学公众号 WPDAXUE
WordPress开发

WordPress 插件开发时在插件列表页的几个常用Hook及用例

2014-5-1 8:11:04

WordPress开发

通过 comment_form() 自定义 WordPress 评论表单

2014-5-11 7:15:32

4 条回复 A文章作者 M管理员
  1. 代码好复杂~

  2. cxd

    有没有这样的插件,就是把鼠标悬停到缩略图上,能显示原图的?

  3. 高端大气,为什么把多说停了?

    • 不想用了,老慢慢的

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索