Click

Writing a plugin for WordPress. To create a page plugin settings (part 4)

Table of contents for the course to create a plugin for WordPress

Show Table of Contents »

  1. Introduction, general information (write a plugin for WordPress. Part 1.)
  2. The General Theory (write a plugin for WordPress. Part 2.)
  3. Preparing to Create the page settings (write a plugin for WordPress. Part 3.)
  4. To create a page plugin settings (write a plugin for WordPress. Part 4.)
  5. The functional component (write a plugin for WordPress. Part 5.)
  6. Internationalization and Russification (write a plugin for WordPress. Part 6.)
  7. Adding to the WordPress.org repository (write a plugin for WordPress. Part 7.)
  8. Source code file for WordPress Plugin

Create settings page for WordPress Plugin

We continue the conversation about how to write a plugin for WordPress.
In the last time we discussed pre-configure wordpress plugin, and now try to write to the administrative page. For a start will give the ability to create the page, and then focus on some points in detail. In principle, the basic information was given in a previous part of the tutorial, here is quite simple code with comments.

Function to create a settings page for the plugin WordPress

A
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
function myplugin_options_page () {/ / Function to create and processing plug-in settings page
global $ wpdb, $ myplugin_prefs_table;
$ Myplugin_options = array (/ / Create an array of plug-in settings
'Myplug_modify_title',
'Myplug_modify_content',
);
$ Cmd = $ _POST ['cmd']; / / Process user input
foreach ($ myplugin_options as $ myplugin_opt) {
$ $ Myplugin_opt = get_option ($ myplugin_opt);
}
if ($ cmd == "del_prefs") {/ / If pressed "delete the phrase" - clean the table settings, plug-in
$ Sql ​​= "TRUNCATE TABLE $ myplugin_prefs_table";
$ Wpdb-> query ($ sql);
?>
__ ( 'All phrases are removed from the database' , 'example_plugin' ) ; ?> </strong></p></div> /* Сообщаем пользвателю об успешной очистке. <div class="updated"> <p> <strong> <? php echo __ ('All phrases are removed from the database', 'example_plugin');?> </ strong> </ p> </ div> / * We report the successful treatment polzvatelyu. * /
<? Php
}
$cmd == "add_prefs" && $_POST [ 'prefs_base' ] ) { //Если введены новые фразы в соотв. if ($ cmd == "add_prefs" && $ _POST ['prefs_base']) {/ / If a new phrase entered in the acc. field - will process them
explode ( " \n " , $_POST [ 'prefs_base' ] ) ; //Ввод разбивается на строки и кладётся в массив, разделитель - перевод строки $ Lines = explode ("\ n", $ _POST ['prefs_base']); / / input is divided into rows and put into an array, separator - line
$lines as $line ) { //Перебираем массив со строками foreach ($ lines as $ line) {/ / iterate through an array of strings
trim ( $line ) ; //Обрезка каждой строки от переводов $ Line = trim ($ line); / / Trim every line of transfers
! $line ) continue ; //Если строка отстутствует - переходим к следующей итерации if (! $ line) continue; / / If the row Out date - go to the next iteration
$title , $body ) = explode ( "|" , $line ) ; //Разделение строки на две подстроки list ($ title, $ body) = explode ("|", $ line); / / Splitting a string into two substrings
/ / Put a substring in the table plugin.
"INSERT INTO $myplugin_prefs_table (title, body) VALUES(' $title ',' $body ')" ; $ Sql = "INSERT INTO $ myplugin_prefs_table (title, body) VALUES ('$ title', '$ body')";
query ( $sql ) ; $ Wpdb -> query ($ sql);
}
?>
__ ( 'Phrases added to the database' , 'example_plugin' ) ; ?> </strong></p></div> /*Сообщаем пользователю об успешной обработке*/ <div class="updated"> <p> <strong> <? php echo __ ('Phrases added to the database', 'example_plugin');?> </ strong> </ p> </ div> / * We report the user about the successful handling * /
<? Php
}
$cmd == "myplugin_save_opt" ) { //Обработка нажатия "Сохранить настройки" if ($ cmd == "myplugin_save_opt") {/ / Processing of clicking "Save Settings"
$myplugin_options as $myplugin_opt ) { //Перебор массива с настройками foreach ($ myplugin_options as $ myplugin_opt) {/ / Iterate the array configuration
$_POST [ $myplugin_opt ] ; //Каждому элементу массива присваиваем введённое пользователем занчение $ $ Myplugin_opt = $ _POST [$ myplugin_opt]; / / assign each element of the array entered by the user zanchenie
}

$myplugin_options as $myplugin_opt ) { //Обновляем настройки плагина в таблице настроек wordpress foreach ($ myplugin_options as $ myplugin_opt) {/ / Update the plugin settings in the table settings wordpress
, $$myplugin_opt ) ; update_option ($ myplugin_opt, $ $ myplugin_opt);
}
?>
__ ( 'Settings saved' , 'example_plugin' ) ; ?> </strong></p></div> <div class="updated"> <p> <strong> <? php echo __ ('Settings saved', 'example_plugin');?> </ strong> </ p> </ div>
<? Php
}
?>
<div class="wrap">
<h2> My Plugin </ h2> / * Page Title Plugin settings * /

__ ( 'Settings' , 'example_plugin' ) ; ?> </h3> /*Название раздела настроек*/ <h3> <? php echo __ ('Settings', 'example_plugin');?> </ h3> / * The name of the section settings * /
/ * Start processing options for the form. The form contains two checkboxes, enable or disable the appropriate plug-in function * /
$_SERVER [ 'REQUEST_URI' ] ; ?> "> <Form method = "post" action = "<? Echo $ _SERVER ['REQUEST_URI'];?>">
<table class="form-table">
<tr>
<th colspan=2 scope="row"> / * The first checkbox - will handle the plug-in header record * /
( $myplug_modify_title ) echo "checked" ; ?> > <?php echo __ ( 'Add random phrase to post title' , 'example_plugin' ) ; ?> <Input name = "myplug_modify_title" type = "checkbox" <? If ($ myplug_modify_title) echo "checked";? >> <? Php echo __ ('Add random phrase to post title', 'example_plugin');?>
</ Th>
</ Tr>
<tr>
<th colspan=2 scope="row"> / * The second checkbox - whether the plug-in to handle the body of records * /
( $myplug_modify_content ) echo "checked" ; ?> > <?php echo __ ( 'Add random phrase to post content' , 'example_plugin' ) ; ?> <Input name = "myplug_modify_content" type = "checkbox" <? If ($ myplug_modify_content) echo "checked";? >> <? Php echo __ ('Add random phrase to post content', 'example_plugin');?>
</ Th>
</ Tr>
</ Table>
<input type="hidden" name="cmd" value="myplugin_save_opt"> / * "functional" part of the button save settings * /
<p class="submit">
'Save Changes' ) ?> " /> /*Вывод кнопки сохранения настроек в браузер. <Input type = "submit" name = "Submit" value = "<? Php _e ('Save Changes')?>" /> / * Output button to save your browser. Standard feature Wordpress * /
</ P>
</ Form> / * End of form processing options * /

/ * Display information about the plugin. For example - who worked * /
__ ( 'Plugin developed' , 'example_plugin' ) ; ?> </h3> <h3> <? php echo __ ('Plugin developed', 'example_plugin');?> </ h3>
<table class="form-table">
<tr> <th>
<ul>
__ ( 'By: <a href="http://www.dimio.org/" target="_blank">dimio</a>' , 'example_plugin' ) ; ?> </li> <li> <? php echo __ ('By: <a href="http://www.dimio.org/" target="_blank"> dimio </ a>', 'example_plugin');?> </ li>
</ Ul>
</ Th> </ tr> </ table>

/ * Block the introduction of new phrases in the table settings, plug-in. The first is the reference for the user * /
__ ( 'Adding phrases' , 'example_plugin' ) ; ?> </h3> <h3> <? php echo __ ('Adding phrases', 'example_plugin');?> </ h3>
/ * Start the input form. The form contains a text field for entering a width of 80 characters and a height of 12 lines * /
<table class="form-table" width="300px">
<tr>
<td>
__ ( 'Format phrases: Title|Body' , 'example_plugin' ) ; ?> <br /> <? Php echo __ ('Format phrases: Title | Body', 'example_plugin');?> <br />
$_SERVER [ 'REQUEST_URI' ] ; ?> "> <Form method = "post" action = "<? Echo $ _SERVER ['REQUEST_URI'];?>">
<textarea cols=80 rows=12 name="prefs_base"> </ textarea> / * Field for entering a new phrase * /
</ Td>
</ Tr>
</ Table>
/ * Button to save phrases. By analogy with the button save settings, but without the use of a standard piano, and Wordpress * /
<input type="hidden" name="cmd" value="add_prefs">
<p class="submit">
__ ( 'Add phrases' , 'example_plugin' ) ; ?> " /> <Input type = "submit" name = "Submit" value = "<? Php echo __ ('Add phrases', 'example_plugin');?>" />
</ P>
</ Form>
/ * The form contains a single button - clean the table settings plugin * /
$_SERVER [ 'REQUEST_URI' ] ; ?> "> <Form method = "post" action = "<? Echo $ _SERVER ['REQUEST_URI'];?>">
<input type="hidden" name="cmd" value="del_prefs">
__ ( 'Remove all phrases from the database' , 'example_plugin' ) ; ?> " /> <Input type = "submit" name = "Submit" value = "<? Php echo __ ('Remove all phrases from the database', 'example_plugin');?>" />
</ Form>
</ Div>

<? Php
/ / End the creation and processing functions of the settings page.
}
?>

I tried to comment in the code all of the key points for understanding, in any case it is worth reading about html and CGI-programming in general. Although in principle - everything is intuitive, and if need be to add new elements to the settings page - please, at least - tell me in which direction to dig.

In the next issue I will examine the functional part of the plug-in for WordPress. I'll tell you how to write a plug-in functions for receiving data from the database and modifying wordpress-publication.
'Add phrases' , 'example_plugin' ) ; ?> – это как раз задел для будущего грамотного перевода (фактически – интернационализации) плагина). Let us then Russification plugin (should have been careful to pay attention to the challenges of the form <?php echo __ ( 'Add phrases' , 'example_plugin' ) ; ?> - this is just the groundwork for a future transfer of literacy (in fact - internationalization) plug-in).
And finally - will show you how to submit your plugin for verification and subsequent publication in the repository WordPress on wordpress.org.
Do not miss out! :)

PS It is still available for download the plugin file is already updated.

More on similar topics:

Category Filed under: SEO , Blogging , Coding | Tag Tags: , , , , , | Comments 11 comments

Comments

11 comments to "Writing a plugin for WordPress. To create a page plugin settings (part 4) "

  1. ArNic writes:

    In general, cool description. But continue to recommend the use of either "case" - or the construction of "if ... ifelse ... else"
    Why not? Well, purely to grasp.
    It is clear that you have a process variable $ cmd is - but you know, be more clear if all these treatments will be a single entity rather than individual terms. By the way there yet, there is one thing: Performance
    Because in your case, the code barybyr (still) will check all the conditions. But by applying the proposed design of the code to reach the desired result, simply stop the further search for conformity. This reduction in CPU time. Another plus point. This readability. When you look design case or "if ... ifelse ... else" you know that this is a common treatment, and then either or. And you can score a commonplace to this block to the desired point :)
    Sorry for the somewhat vague text say never normally could not.

    • dimio writes:

      The idea is clear in principle. Rewritten in the form of if {} elsif {} will be reasonable.
      In order to reduce CPU time needed to iterate through the options to build the most probable sequence, and not, as they now stand.

  2. Hilarion writes:

    Well, you really zhzhosh! So much code, but still no decent explanation! :-) While 3 + is the maximum :-) Tip: You write so that people could understand and interesting, not only you, dear author!

    • ArNic writes:

      In vain. I agree that the code is not the best - but the comments are very clear.

      • Hilarion writes:

        Well, it's not that bad code, no! Just once it moved too quickly, as they say, no foreplay :-) . We had to somehow share the previous posts this information to even the kettle (whom I am not), it was all clear. But I have questions and issues ...

        • ArNic writes:

          Of course, only the author at the beginning of a slip that he had learned php it is because of the desire to write a plugin. IMHO for the inexperienced programmer - article no.

  3. Shua writes:

    Did all of the examples to create page. I decided to check out. When you activate the plugin error message: "Plugin produced by activation of 292 characters unexpected conclusion. ... "
    Notepad + +, UTF-8 without BOM
    WP 3.1.1

    • dimio writes:

      3.1.1 I have not. Last thing checked - 2.9.2.
      In the process of writing these notes I made a plugin that I have now is working on version 3.1. ( [Link] .) You can compare with him, there is an error or not.

Leave a Reply