Создание базового плагина на WordPress (Base WordPress Plugin creating)

5,612 views

Published on

Slide from WordPress MeetUp Moscow #13
plugin example link to download http://yadi.sk/d/x9hDWGH33KUNI

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
5,612
On SlideShare
0
From Embeds
0
Number of Embeds
1,878
Actions
Shares
0
Downloads
21
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Создание базового плагина на WordPress (Base WordPress Plugin creating)

  1. 1. Базовый плагин WordPress1. Структура плагина2. Работа с action’ами WordPress3. Локаль в WordPress4. Правильное подключение стилей и скриптов5. AJAX в WordPress с помощью jQuery и JSON6. Определение версии WordPress7. Работа с API Media Uploader в зависимости от версии WordPress, втч новый Media Uploader
  2. 2. Создаем структуру плагина/wp-content/plugins/my-plugin/wp-content/plugins/my-plugin/css/wp-content/plugins/my-plugin/css/my_plugin.css/wp-content/plugins/my-plugin/images/wp-content/plugins/my-plugin/images/my_plugin_icon.png/wp-content/plugins/my-plugin/js/wp-content/plugins/my-plugin/js/my_plugin.js/wp-content/plugins/my-plugin/languages/wp-content/plugins/my-plugin/my-plugin-functions.php/wp-content/plugins/my-plugin/my-plugin.php
  3. 3. my-plugin.php (1) Пока как-то так:/*Plugin Name: My PluginPlugin URI: http://www.my-plugin.ru/Description: My Plugin DescriptionAuthor: Igor SazonovVersion: 1.0Author URI: https://twitter.com/tigusigalpa*/include_once(plugin_dir_path(__FILE__)./my-plugin-functions.php);
  4. 4. my-plugin-functions.php (1) Определяем вспомогательные переменные$my_plugin_name = my-plugin;
  5. 5. my-plugin-functions.php (2) Определяем папку для хранения переводов локалейfunction my_plugin_init() { global $my_plugin_name; $current_locale = get_locale(); if(!empty($current_locale)) { load_plugin_textdomain($my_plugin_name, false, $my_plugin_name."/languages/"); }}add_action(init, my_plugin_init);
  6. 6. my-plugin-functions.php (3) Делаем для плагина свой пункт меню в админкеfunction my_plugin_add_menu() { global $my_plugin_name; $page = add_menu_page(__(My Plugin page name,my-plugin), $my_plugin_name, activate_plugins,__FILE__, my_plugin_index,plugins_url(images/my_plugin_icon.png, __FILE__)); add_action(admin_print_scripts- . $page,my_plugin_admin_scripts);}add_action(admin_menu, my_plugin_add_menu);
  7. 7. my-plugin.php (2) Вывод HTML разметки страницы плагинаfunction my_plugin_index() { if(!is_user_logged_in()) die(-1);?> <div class="wrap columns-2"> <div id="poststuff"> <div id="post-body" class="metabox-holder columns-2"> <div id="post-body-content"> <a class="button my-plugin-button" href="javascript:;"><?php _e(Open Media library, my-plugin);?></a><br /> <div id="my-plugin-div"></div> </div> <div id="postbox-container-1" class="postbox-container"> </div> </div> </div> </div><?php }?>
  8. 8. my-plugin-functions.php (4) Функция определения версии WordPressfunction my_plugin_get_wp_version() { global $wp_version; return $wp_version;}
  9. 9. my-plugin-functions.php (5) Инициализация скриптов и стилей плагина и создание nonce’a для верификации запроса в AJAXfunction my_plugin_admin_scripts_init() { global $my_plugin_name; wp_register_script(my-plugin-js, plugins_url(js/my_plugin.js, __FILE__), array(jquery)); wp_register_style(my-plugin-css, plugins_url(css/my_plugin.css, __FILE__)); $array = array( wp_version_new => (version_compare(my_plugin_get_wp_version(), 3.5, >=))?1:0, security => wp_create_nonce(my-plugin-action), title => __(Sample Title, my-plugin), button_title => __(Button Title, my-plugin) ); wp_localize_script(my-plugin-js, mp_array, $array);}add_action(admin_init, my_plugin_admin_scripts_init);
  10. 10. my-plugin-functions.php (6) Правильное подключение стилей и js-скриповfunction my_plugin_admin_scripts() { if(version_compare(my_plugin_get_wp_version(), 3.5, >=) &&function_exists(wp_enqueue_media)) { wp_enqueue_media(); wp_enqueue_script(media-upload); wp_enqueue_style(media); } else { wp_enqueue_script(thickbox); wp_enqueue_style(thickbox); } wp_enqueue_script(my-plugin-js); wp_enqueue_style(my-plugin-css);}
  11. 11. my-plugin-functions.php (7) + JS Создание AJAX-action’a плагина для Тизер функции на JS/jQuery версий WordPress ниже 3.5 (мы надеемся что это будет версия 3.3 =) jQuery.post(ajaxurl, {html:html,sec:array.security,action:my_plugin_afunction my_plugin_ajax_action_wp33() { ction_wp33}, function(data) { global $my_plugin_name; if(data.res) { check_ajax_referer(my-plugin-action, sec); jQuery("#my-plugin-div").html(data.code); $ret_array = array(); } $ret_array[res] = false; }, "json" $html = trim(stripcslashes($_POST[html])); ); $ret_array[code] = $html; if($html && $ret_array[code]) { $ret_array[res] = true; } die(json_encode($ret_array));}add_action(wp_ajax_my_plugin_action_wp33,my_plugin_ajax_action_wp33);
  12. 12. my-plugin-functions.php (8) + JS Создание AJAX-action’a плагина для Тизер функции на JS/jQuery версий WordPress выше или 3.5 jQuery.post(ajaxurl,function my_plugin_ajax_action_wp35() { {link:attachment.link,url:attachment.url,sec:array. security,action:my_plugin_action_wp35}, global $my_plugin_name; function(data) {check_ajax_referer(my-plugin-action, sec); if(data.res) { $ret_array = array(); jQuery("#my-plugin-div").html(data.code); $ret_array[res] = false; } $link = trim(stripcslashes($_POST[link])); }, "json" $url = trim(stripcslashes($_POST[url])); ); $ret_array[code] = "<a href="{$link}"target="_blank"><img src="{$url}"/></a>"; if($link && $url && $ret_array[code]) { $ret_array[res] = true; } die(json_encode($ret_array));}add_action(wp_ajax_my_plugin_action_wp35, my_plugin_ajax_action_wp35);
  13. 13. my_plugin.js (1)jQuery(document).ready(function(){ jQuery(document).on(click, .my-plugin-button,function(event) { if(mp_array.wp_version_new < 1) { //to do if WP version less 3.5 } else { //to do if WP version greater or equal 3.5 } });});
  14. 14. my_plugin.js(2) Версия WP < 3.5 (1)tb_show(mp_array.title,media-upload.php?TB_iframe=true);if((window.original_tb_remove == undefined) &&(window.tb_remove != undefined)) { window.original_tb_remove = window.tb_remove; window.tb_remove = function() { window.original_tb_remove(); };}
  15. 15. my_plugin.js (3) Версия WP < 3.5 (2)window.original_send_to_editor = window.send_to_editor;window.send_to_editor = function(html) {jQuery.post(ajaxurl, {html:html,sec:mp_array.security,action:my_plugin_action_wp33}, function(data) { if(data.res) { jQuery("#my-plugin-div").html(data.code); } }, "json");tb_remove();}return false;
  16. 16. my_plugin.js (4) Версия WP >= 3.5 (1)var custom_file_frame;event.preventDefault();if(typeof(custom_file_frame)!=="undefined") { custom_file_frame.close();}custom_file_frame = wp.media.frames.customHeader = wp.media({ title: mp_array.title, library: {type: image}, button: {text: mp_array.button_title}, multiple: false});
  17. 17. my_plugin.js (5) Версия WP >= 3.5 (2)custom_file_frame.on(select, function() {var attachment = custom_file_frame.state().get(selection).first().toJSON();jQuery.post(ajaxurl,{link:attachment.link,url:attachment.url,sec:mp_array.security,action:my_plugin_action_wp35}, function(data) { if(data.res) {jQuery("#my-plugin-div").html(data.code);} }, "json");});custom_file_frame.open();
  18. 18. Спасибо за внимание! Вопросы

×