为主题添加可定制的小工具

2011年02月13日14:35:07 7 7,362

对主题开发者很有用处的技术文章,外语不好就不给大家翻译了,自行参阅。

So you’re a designer and you create beautiful looking themes for WordPress. However you find it quite hard making your beautiful theme come to life when trying to integrate it with WordPress. Or maybe you’re getting the hang of this whole “coding” thing (you know HTML and CSS after all) but you need a helping hand to lead you in the right direction when it comes to the more complex PHP stuff in WordPress. Or maybe you’re simply looking for a comprehensive tutorial on a certain aspect of WordPress programming.

If you are any of these people then this series of tutorials is for you. In this series I will cover most of the popular programming topics that designers tend to struggle with when doing development work for WordPress. You might even find that it’s not as hard as you think.

Part 1 – How to Build Custom Widgets for Your Themes

为主题添加可定制的小工具
One of the most common features of almost every theme that has ever existed is the ability to customize your sidebar with widgets.

“WordPress Widgets (WPW) is like a plugin, but designed to provide a simple way to arrange the various elements of your sidebar content (known as “widgets”) without having to change any code.”

WordPress Codex

Widgets provide WordPress users an easy way to customize content without having to code anything. Unfortunately that means that it is down to theme developers to do it. But don’t worry it might not be as bad as you think. Since v2.8 WordPress has come packaged with a Widget API which makes it really easy to create custom widgets for your themes, and this is what we will be using to create our example widget.

Using the Widgets API

To create a new widget using the Widgets API you simply need to create a class that extends the standard widget class. Don’t worry if you don’t know what that means, because all you have to do is open up your functions.php file and paste the following code:

  1. class My_Widget extends WP_Widget
  2. {
  3. function My_Widget() {
  4. // register the widget
  5. }
  6. function widget($args, $instance) {
  7. // output the content of the widget
  8. }
  9. function form($instance) {
  10. // output the admin options form
  11. }
  12. function update($new_instance, $old_instance) {
  13. // processes the admin options form when saved
  14. }
  15. }
  16. add_action('widgets_init', create_function('', 'return register_widget("My_Widget");'));

This is the template code for your widget. Obviously you can rename each instance of “My_Widget” above to something more appropriate. The important thing to notice here is the four functions which will hold all of the functionality of our widget. It’s easier to explain what these functions do by showing you an example of a widget and explaining how these four functions make it work. So that’s exactly what I’ll do.
Our Newsletter Signup Widget

For this example we are going to create a simple widget that lets users enter a title, some descriptive text and paste in their favourite newsletter signup form code (like MailChimp or CampaignMonitor for example). You will be able to change the title, description and code of the widget from the widget admin. So let’s get coding!

  1. class Newsletter_Signup_Widget extends WP_Widget
  2. {
  3. // Register the widget
  4. function Newsletter_Signup_Widget() {
  5. // Set some widget options
  6. $widget_options = array( 'description' => 'Allow users to signup to your newsletter easily', 'classname' => 'newsletter-signup' );
  7. // Set some control options (width, height etc)
  8. $control_options = array( 'width' => 300 );
  9. // Actually create the widget (widget id, widget name, options...)
  10. $this->WP_Widget( 'newsletter-signup-widget', 'Newsletter Signup', $widget_options, $control_options );
  11. }

First we create a new class that “extends WP_Widget” then we setup the widget in what is known as a constructor (a function with the same name as the class). Don’t worry about the technicalities here. Just accept that you need them and this is how they work.

In our constructor function first we set up some options in the $widget_options and $control_options variables. These are arrays of values that we pass into the WP_Widget() function to create our widget. The important values here are the description in $widget_options which will appear below your widget on the Widgets page, and the width (you can also specify height) in $control_options which will set the width of the widget admin box (when it is expanded).

Then we call the important WP_Widget() function. The four parameters that you need to pass in to this function are: a unique widget id (lowercase with no spaces), a widget title (which will be used on the widget admin), the $widget_options variable and finally the $control_options variable. Now we have setup our widget we can move on to the next function.

  1. // Output the content of the widget
  2. function widget($args, $instance) {
  3. extract( $args ); // Don't worry about this
  4. // Get our variables
  5. $title = apply_filters( 'widget_title', $instance['title'] );
  6. $text = $instance['text'];
  7. $code = $instance['code'];
  8. // This is defined when you register a sidebar
  9. echo $before_widget;
  10. // If our title isn't empty then show it
  11. if ( $title ) {
  12. echo $before_title . $title . $after_title;
  13. }
  14. // If our description isn't empty then show it
  15. if ( $text ) {
  16. echo '<p>'. $text .'</p>';
  17. }
  18. // If we have some code then output it
  19. if ( $code ) {
  20. echo $code;
  21. }
  22. // This is defined when you register a sidebar
  23. echo $after_widget;
  24. }

The widget() function is where we code the output that the users will see on your theme. Here we get the $title, $text and $code variables that are stored in the $instance array and simply echo them if they are not empty. If you need to do any HTML formatting of your content then here is the place to do it, but in our example we don’t need much.

Note that here we also echo four variables ($before_widget, $after_widget, $before_title, $after_title) that are defined when registering sidebars. Technically it is not essential to include these variables but if you leave them out you’re sidebar might become messed up and it certainly won’t be very flexible (especially if you are designing a theme that you want to distribute). So take my advice and just include them. Then we can move on.

  1. // Output the admin options form
  2. function form($instance) {
  3. // These are our default values
  4. $defaults = array( 'title' => 'Example', 'text' => 'Subscribe to our newsletter using the form below.', 'code' => '' );
  5. // This overwrites any default values with saved values
  6. $instance = wp_parse_args( (array) $instance, $defaults );
  7. ?>
  8. <p>
  9. <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label>
  10. <input id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo $instance['title']; ?>" type="text" class="widefat" />
  11. </p>
  12. <p>
  13. <label for="<?php echo $this->get_field_id('text'); ?>"><?php _e('Description:'); ?></label>
  14. <input id="<?php echo $this->get_field_id('text'); ?>" name="<?php echo $this->get_field_name('text'); ?>" value="<?php echo $instance['text']; ?>" type="text" class="widefat" />
  15. </p>
  16. <p>
  17. <label for="<?php echo $this->get_field_id('code'); ?>"><?php _e('Code:'); ?></label>
  18. <textarea id="<?php echo $this->get_field_id('code'); ?>" name="<?php echo $this->get_field_name('code'); ?>" rows="10" class="widefat"><?php echo $instance['code']; ?></textarea>
  19. </p>
  20. <?php
  21. }

The form() function is where we put the HTML that will appear in the admin form (when a widget is expanded). In our example we are going to need two text inputs (for the title & description) and a text area (for the code).

But before we create the HTML for the form we are going to set up some variables. $defaults is simply an array which holds our default values that will appear when you first add the widget to a sidebar in the widget admin. Don’t worry too much about the wp_parse_args() function. All this does is set up $instance with our array of values. If we have saved values then they will be used, otherwise it fall’s back to the $defaults.

Setting up the form itself is just basic HTML. We set the values of the HTML inputs using the $instance array which, again, is basic PHP. The thing to note is the WordPress helper functions that are used to make sure we get the input id’s and names right. Setting the id’s and names manually would be a nightmare (imagine loads of widgets made by different developers all with different id’s and names). So we just let WordPress do it for us and ask no questions. One more function to go.

  1. // Processes the admin options form when saved
  2. function update($new_instance, $old_instance) {
  3. // Get the old values
  4. $instance = $old_instance;
  5. // Update with any new values (and sanitise input)
  6. $instance['title'] = strip_tags( $new_instance['title'] );
  7. $instance['text'] = strip_tags( $new_instance['text'] );
  8. $instance['code'] = $new_instance['code'];
  9. return $instance;
  10. }
  11. }

The update() function is where you process the data when a user clicks “Save” on the widget admin. This function should return a variable with all of your settings (in this case the $instance variable). The code is fairly self explanatory here. Just note that the names of the array indexes (the bit in square brackets) matches the names of your inputs in the functions above.

Also remember that it is your responsibility to sanitise user input when you are saving data, hence the use of the strip_tags() function to strip any nasty HTML from our variables.

  1. add_action('widgets_init', create_function('', 'return register_widget("Example_Widget");'));

Finally we need to “hook” our new widget into WordPress using the add_action() function. I’m not going to explain how WordPress actions work in this article, suffice to say you must include this line for your code to function properly.
Full Code Listing

  1. class Newsletter_Signup_Widget extends WP_Widget
  2. {
  3. // Register the widget
  4. function Newsletter_Signup_Widget() {
  5. // Set some widget options
  6. $widget_options = array( 'description' => 'Allow users to signup to your newsletter easily', 'classname' => 'newsletter-signup' );
  7. // Set some control options (width, height etc)
  8. $control_options = array( 'width' => 300 );
  9. // Actually create the widget (widget id, widget name, options...)
  10. $this->WP_Widget( 'newsletter-signup-widget', 'Newsletter Signup', $widget_options, $control_options );
  11. }
  12. // Output the content of the widget
  13. function widget($args, $instance) {
  14. extract( $args ); // Don't worry about this
  15. // Get our variables
  16. $title = apply_filters( 'widget_title', $instance['title'] );
  17. $text = $instance['text'];
  18. $code = $instance['code'];
  19. // This is defined when you register a sidebar
  20. echo $before_widget;
  21. // If our title isn't empty then show it
  22. if ( $title ) {
  23. echo $before_title . $title . $after_title;
  24. }
  25. // If our description isn't empty then show it
  26. if ( $text ) {
  27. echo '<p>'. $text .'</p>';
  28. }
  29. // If we have some code then output it
  30. if ( $code ) {
  31. echo $code;
  32. }
  33. // This is defined when you register a sidebar
  34. echo $after_widget;
  35. }
  36. // Output the admin options form
  37. function form($instance) {
  38. // These are our default values
  39. $defaults = array( 'title' => 'Example', 'text' => 'Subscribe to our newsletter using the form below.', 'code' => '' );
  40. // This overwrites any default values with saved values
  41. $instance = wp_parse_args( (array) $instance, $defaults );
  42. ?>
  43. <p>
  44. <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label>
  45. <input id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo $instance['title']; ?>" type="text" class="widefat" />
  46. </p>
  47. <p>
  48. <label for="<?php echo $this->get_field_id('text'); ?>"><?php _e('Description:'); ?></label>
  49. <input id="<?php echo $this->get_field_id('text'); ?>" name="<?php echo $this->get_field_name('text'); ?>" value="<?php echo $instance['text']; ?>" type="text" class="widefat" />
  50. </p>
  51. <p>
  52. <label for="<?php echo $this->get_field_id('code'); ?>"><?php _e('Code:'); ?></label>
  53. <textarea id="<?php echo $this->get_field_id('code'); ?>" name="<?php echo $this->get_field_name('code'); ?>" rows="10" class="widefat"><?php echo $instance['code']; ?></textarea>
  54. </p>
  55. <?php
  56. }
  57. // Processes the admin options form when saved
  58. function update($new_instance, $old_instance) {
  59. // Get the old values
  60. $instance = $old_instance;
  61. // Update with any new values (and sanitise input)
  62. $instance['title'] = strip_tags( $new_instance['title'] );
  63. $instance['text'] = strip_tags( $new_instance['text'] );
  64. $instance['code'] = $new_instance['code'];
  65. return $instance;
  66. }
  67. }
  68. add_action('widgets_init', create_function('', 'return register_widget("Newsletter_Signup_Widget");'));

Over to You

So now that you know how to create custom widgets for your themes in WordPress, let me know how you get on. I hope this article has been easy enough to follow but comprehensive enough to give you a good introduction to creating widgets for WordPress.

相关文章:

weinxin
我的微信
分享交流WordPress经验与技巧,关注前端设计与网站制作。仅用于功能演示。
Begin主题购买
Begin主题购买

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

目前评论:7   其中:访客  6   博主  0   引用   1

    • sand 3

      四级 表示压力很大 –!

      • 小司 3

        四级未过,表示压力很大!

        • 憨豆先生 6

          鸟哥下面评论的贴图功能是怎么实现的?求教程!

          • 碎语人生 5

            看过后很茫然。

            • ★Extreme★ 4

              一大堆鸡肠!!都看傻眼了……

              • 电脑配置 2

                看起来有点吃力啊。。

              • 来自外部的引用: 1

                • WP升級到3.1.1了 » 卡咪嘎米's blo