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

发布时间:2020-05-05

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

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

wordpress Themes” src=”https://dev7studios.com/wp-content/uploads/2011/01/widgets1.jpg” alt4=”” width=”460″ height=”190″ alt=”为主题添加可定制的小工具” />
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.

相关文章:

大熊wordpress凭借多年的wordpress企业主题制作经验,坚持以“为用户而生的wordpress主题”为宗旨,累计为2000多家客户提供品质wordpress建站服务,得到了客户的一致好评。我们一直用心对待每一个客户,我们坚信:“善待客户,将会成为终身客户”。大熊wordpress能坚持多年,是因为我们一直诚信。我们明码标价(wordpress做网站需要多少钱),从不忽悠任何客户,我们的报价宗旨:“拒绝暴利,只保留合理的利润”。如果您有网站建设、网站改版、网站维护等方面的需求,请立即咨询右侧在线客服或拨打咨询热线:18324743309,我们会详细为你一一解答你心中的疑难。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

相关文章

写给所有做网站的朋友的一封信

写给所有做网站的朋友的一封信

现在就开始执行“1+N”互联网推广和没有开始执行的人,一两天看不出任何区别; 一两个月看来差异也是微乎其微的;但在2-5年的长远时间来看的时候,你的高质量询盘不断增加,你的互联网资产已经建立完成,对手已经很难匹敌,现在你看到这段文字的时候就是最好的开始,现在就是最好的时候,马上开始“1+N”体系的整体互联网推广吧,我们和你一起,开创互联网大未来!

点击查看详情

准备开启WordPress网站建设推广?

我们相信高端漂亮的网站不应该是昂贵的,这就是wordpress对每个人都是免费的原因
wordpress建站免费入门,并提供价格合理的wordpress建站套餐。