Writing a plugin for WordPress. Preparations for the establishment of the settings page (Part 3).
Contents of the course create a plugin for WordPress
- Introduction, general information (write a plugin for WordPress. Part 1.)
- The General Theory (write a plugin for WordPress. Part 2.)
- Preparing to Create the page settings (write a plugin for WordPress. Part 3.)
- To create a page plugin settings (write a plugin for WordPress. Part 4.)
- Functional component (write a plugin for WordPress. Chapter 5.)
- Internationalization and Russification (write a plugin for WordPress. Part 6.)
- Adding to the repository WordPress.org (write a plugin for WordPress. Chapter 7.)
- Source code file plugin for WordPress
'myplugin_set_options' ) ; , где __FILE__ будет автоматически заменено на вызов файла плагина). So, we already know how to call a function settings for the plugin in the process of installing it (by calling register_activation_hook ( __FILE__ , 'myplugin_set_options' ) ; , where __FILE__ will be automatically changed to call the file plugin). Now, in order to write a WordPress plugin, we need to set the default options (creating the appropriate entries in the table prefix_options *) and create a settings page where the user can control the behavior of the plugin.
* Prefix_options - mySQL table settings with wordpress. Prefix is specified in the file wp-config to install wordpress and has a default zanchenie wp (ie, a table called wp_options).
Create and delete options when writing wordpress plugin
Creating the default settings and table settings, plug-in.
As you may remember from the second part of this manual, for example, I decided to write a plugin wordpress, changing the title, body and recording the time of publication. This means that the plug must be somewhere to take the data needed to be replaced. Why do we create a separate table with the data plug-in. So:
- Gets the prefix table names for the wordpress-blog to write a plugin created a table of their preferences with the same prefix in the name myplugin_get_table_handle ( ) ; # в этой переменной будет содержаться имя таблицы с настройкам написанного нами плагина wordpress $ Myplugin_prefs_table = myplugin_get_table_handle (); # this variable will contain the name of a table setting with our written wordpress plugin
function myplugin_get_table_handle () {
; # класс wordpress для работы с БД global $ wpdb; # class to work with wordpress database
-> prefix . "myplugin_preferences" ; # создаём имя таблицы настроек плагина return $ wpdb -> prefix. "myplugin_preferences"; # create a name for the table settings, plug-in
} - Install the plug-in default settings in the table wordpress prefix_options and create our own table settings 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
39function myplugin_set_options () {
; global $ wpdb;
, 0 ) ; # будет ли плагин по умолчанию обрабатывать заголовки записей. add_option ('myplug_modify_title', 0) # whether the default plugin to process the headers of records. 0 - no
, 1 ) ; # --||-- тело записей. add_option ('myplug_modify_content', 1) # --||-- body of records. 1 - yes
wpsig_get_table_handle ( ) ; # вызов функции повторяется, т. к. данные действия происходят на этапе установки плагина, когда вызов в теле еще не может быть осуществлён $ Myplugin_prefs_table = wpsig_get_table_handle (); # function call is repeated, because these actions occur at the stage of installing the plugin, when the call is still in the body can not be implemented
'' ; # кодировка БД $ Charset_collate =''; # encoding DB
version_compare ( mysql_get_server_info ( ) , '4.1.0' , '>=' ) ) if (version_compare (mysql_get_server_info (), '4 .1.0 ','> = '))
"DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci" ; # устанавливаем уникод $ Charset_collate = "DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci"; # install unicode
$wpdb -> get_var ( "SHOW TABLES LIKE ' $myplugin_prefs_table '" ) != $myplugin_prefs_table ) { # если таблица настроек плагина еще не создана - создаём if ($ wpdb -> get_var ("SHOW TABLES LIKE '$ myplugin_prefs_table'")! = $ myplugin_prefs_table) {# if table settings, plug-in does not exist yet - creating
"CREATE TABLE `" . $myplugin_prefs_table . "` ( $ Sql = "CREATE TABLE` ". $ Myplugin_prefs_table." `(
`Id` INT NOT NULL AUTO_INCREMENT,
`Title` VARCHAR (255) NOT NULL default'',
`Body` VARCHAR (255) NOT NULL default'',
UNIQUE KEY id (id)
) $ Charset_collate ";
ABSPATH . 'wp-admin/includes/upgrade.php' ) ; # обращение к функциям wordpress для require_once (ABSPATH. 'wp-admin/includes/upgrade.php'); # function calls for wordpress
) ; # работы с БД. dbDelta ($ sql); # work with the database. create a new table
}
}
</ Pre>
ul > </ Li> </ ul>
пишем плагин </ strong >, мы должны знать , как в дальнейшем работать с его опциями : Once we have <strong> write a plugin </ strong>, we need to know how to continue working with its options:
font color = "#CC33CC" > add_option </ font ></ em > — функция < strong > wordpress </ strong >, создающая новые записи в таблице < em > prefix_options </ em >; <Em> <font color = "# CC33CC"> add_option </ font> </ em> - function <strong> wordpress </ strong>, which creates new entries in the table <em> prefix_options </ em>;
font color = "#CC33CC" > get_option </ font ></ em > – функция , извлекающая значение настроек ; <Em> <font color = "# CC33CC"> get_option </ font> </ em> - a function that retrieves the value of options;
font color = "#CC33CC" > update_option </ font ></ em > служит для обновления записей ( настроек ) , а <Em> <font color = "# CC33CC"> update_option </ font> </ em> is used to update records (settings), and
font color = "#CC33CC" > delete_option </ font ></ em > используется для их удаления . <Em> <font color = "# CC33CC"> delete_option </ font> </ em> is used to remove them.
"128_ %d 1%83 %d 0 %b 4 %d 0 %b 0 %d _1" > Удаление настроек плагина при деинсталляции </ h2 > <H2 id = "128_% d 1% 83% d 0% b% d 4 0 0% b% d _1"> Delete settings when uninstalling the plugin </ h2>
"true" lang = "php" line_numbers = "false" > <Code escaped = "true" lang = "php" line_numbers = "false">
function myplugin_unset_options () {
, $myplugin_prefs_table ; global $ wpdb, $ myplugin_prefs_table;
) ; delete_option ('myplug_modify_title');
) ; delete_option ('myplug_modify_content');
"DROP TABLE $myplugin_prefs_table " ; $ Sql = "DROP TABLE $ myplugin_prefs_table";
query ( $sql ) ; $ Wpdb -> query ($ sql);
}Creation and the plugin settings page.
Now that we have written the plugin for wordpress, already has functions to create, install and uninstall setup, it's time to think about to write interfyes allowing these settings to control. Control settings wordpress plugins made by means of the relevant paragraphs of the administrative menu, which are in fact the settings page.
Placing links to plug-in settings page.
First, you must decide where we will post a link to a page with the settings of our wordpress plugin. The options - to place her in the main administrative menu wordpress (for example, after the item "Settings", it is recommended to do so only if your plugin makes some significant changes in functional wordpress and a separate menu for it is necessary), or to place Settings page in the "Settings" (this is how we proceed.) write a plug-in the following code:
function myplugin_admin_page () {
, 'MyPluginButton' , 8 , __FILE__ , 'myplugin_options_page' ) ; add_options_page ('MyPlugin', 'MyPluginButton', 8, __FILE__, 'myplugin_options_page');
}Let me explain what's going on here:
add_options_page - called a standard feature of wordpress to install the settings page.
MyPlugin - header settings page plugin;
MyPluginButton - name of the button in the menu, which is used to go to the settings page;
8 - the level of user access rights, which will be visible button (in this case - not less than an administrator), the greater the number - the higher must be right;
__FILE__ - Call the file from our plugin (if the function responsible for working with the page settings are not in the main script file, you must specify the path to them). For larger plug with a complex structure may be required.
myplugin_options_page - name of the function that seeks to build the page settings, and further work with it.Formation of the page with the settings
With the placement of the button-link to the page settings, we decided, we continue to write plug-in.
Now I only briefly list the main principles and ways of creating the settings page, as a function of its creation - the largest (in terms of code) in our test plugin and it is worthy of parsing with detailed comments in a separate, following part of the guide on "How to write a plugin wordpress ".So, the plugin settings page in wordpress is an ordinary html page (like this here corny way of the world
), Within which are various fields for user input. To understand the structure of this page, you must be familiar with cgi-programming in general (who are interested - look for books on the cgi-Programming " Library "). If you explain your fingers, it looks like this: - derivation of general information (title, description, information, etc.);
- create a form (all work with user input is organized by the withdrawal forms and further obtain their parameters);
- establishment within the form fields for user input (switches, checkboxes, radio buttons, drop-down menu in the form of lists, fields for entering text, etc.);
- receipt of forms of user input;
- data processing (checking for compliance with certain criteria, perform an action on data, etc.)
- return processing results to the user entered their data (in our case - marked by a tick checkbox marked "Settings saved", etc.)
Thus, in the next part of the manual "Writing a plugin for WordPress" I'll look at how to perform the algorithm described above. We will create a plug-in configuration page with checkboxes to select the mode of work and a text field intended for the user enters words that will continue to operate when the plug-in header and body of records before they are published.
You can download the plugin file to review the code. As the publication of new parts of the manual file will be updated.
All the success!
More on similar topics:
Filed under: SEO , Blogging , Coding |
Tags: How-to , plugin , WordPress , blog , programming , promotion |
11 comments



Many thanks to the author for the work done! The real benefit for writing plug-ins, though of course the questions will arise, particularly if the level of programming is not great. Look for our questions!
Constantly re-read your articles. Store them on the computer and then re-read
When you activate the plugin get the error message -
Call to undefined function wpsig_get_table_handle () in wp \ wp-content \ plugins \ example_plugin.php on line 21
Function in the example is myplugin_get_table_handle, forgot to fix.
dimio writes:
I thought so, too, and replaced wpsig_get_table_handle () on myplugin_get_table_handle ()
But in the end:
Warning: call_user_func_array () [function.call-user-func-array]: First argument is expected to be a valid callback, 'wpsignaturer_admin_page' was given in E: \! Web \!! Www \ wp \ wp-includes \ plugin . php on line 339
If not difficult, then test your example, reference to which you give.
I would be very grateful if you could correct the mistake, it is very much want to understand, but do not know where the herd ...
Check at your leisure. Did you download this plugin here: He and working on his image and likeness of example I was doing.
Thank you and have a look.
Do not tell me how to add plug-in ability to add individual data to a specific post. That is, when the plug-in has its own field in the editing of fasting?
If I understand the question - it must be done through "arbitrary fields (custom fields)". Read here for example:
They are created funetsiey wordpress add_post_meta - (English)
And the most comprehensive information (also in English.)
Well, with every post better and better
And I do not want to wish you a dimio, author and drink riddle!
But seriously, I advise you in positions to give any example of writing a plugin. That is the course of this mini-podkursa author himself, that is, do you tell how to write a particular plug-in, for example., a plug-pagination or captcha
But if the talent to php not, you can disassemble postochno At least some ready-made plug-in
Burn, author!
How to place a link after the "Options" menu?
To do this, And in it (if necessary) to add their menu: