K 的个人资料Some Say...you are bette...照片日志列表 工具 帮助

日志


2009/11/23

How to create a wordpress widget control panel

How to create a wordpress widget control panel

For my curiosity, I tried to create a simple Wordpress widget the other day to find out how it works. There is a ton of posts online to tutor you from scratch. Some of them are very clear and helpful. I recommend the following:
As for me, I tried to realize a widget with database activities, i.e. to create and drop tables, insert and update records. There is another one from Wordpress Codex which is ultimately helpful.
This post is in no place to substitute any of them listed above. However, when I was trying with my idea, everything works together well except that the code in the control panel method of my widget always gets executed twice! In terms of database, that is redundant data.

If you did follow those posts, your widget's control panel method will look like this:


01//Control panel method
02 function control(){
03  //essential declaration
04  global $wpdb;
05  //set table name again
06  $table_name = $wpdb->prefix . "mytable";
07  //test if the form is submit,that is the save button clicked, get the arguments from the form
08  if ( isset($_POST['mywidget-submit'])){
09   //some parameter transaction here
10    
11   //prepare query
12   $insertsql='INSERT INTO '
13    .$table_name
14    .'(a,b,c,d,e)'
15    .'VALUES'
16    .'( A,B,C,D,E);';
17    //execute query and write into database
18    $wpdb->query( $insertsql );
19  
20   }
21     
22  }
23  //design the control panel form here and output
24  $control_form='<input name="mywidget-submit" value="1" type="hidden">'
25  echo $control_form;
26 }


It is absolutely right and working. If you are just using add,update,delete_option (refer to the Wordpress functions) to manipulate your parameters. This is totally fine. In my case, the INSERT statement will be run twice every time the "Save" button is hit on the widget control panel.

Here is how it works:
When the "Save" button is pressed,the "hidden" input control in our control panel form is submitted and the whole is method is called. Now that we test the value from $_POST if the "hidden" control is submit and run the code to insert the Sql statement.

I suspect that when it is done, the control panel will be reloaded again by Wordpress however the $_POST['mywidget-submit'] status is never changed. That's why it happens twice every time.

My solution to this is simple (I believe this is not a perfect one. Let me know if you have others.) To explicitly unset the &_POST['mywidget-submit'] when the code is run, in this case, just after the Sql statement is issued.

1//unset the post array otherwise the query is run twice
2unset($_POST['mywidget-submit']);