SlideShare uma empresa Scribd logo
1 de 18
Baixar para ler offline
Базовый плагин WordPress
1.   Структура плагина
2.   Работа с action’ами WordPress
3.   Локаль в WordPress
4.   Правильное подключение стилей и скриптов
5.   AJAX в WordPress с помощью jQuery и JSON
6.   Определение версии WordPress
7.   Работа с API Media Uploader в зависимости от
     версии WordPress, втч новый Media Uploader
Создаем структуру плагина
/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
my-plugin.php (1)
                          Пока как-то так:
/*
Plugin Name: My Plugin
Plugin URI: http://www.my-plugin.ru/
Description: My Plugin Description
Author: Igor Sazonov
Version: 1.0
Author URI: https://twitter.com/tigusigalpa
*/

include_once(plugin_dir_path(__FILE__).'/my-plugin-functions.php');
my-plugin-functions.php (1)
 Определяем вспомогательные переменные

$my_plugin_name = 'my-plugin';
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');
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');
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 }?>
my-plugin-functions.php (4)
  Функция определения версии WordPress

function my_plugin_get_wp_version() {
  global $wp_version;
  return $wp_version;
}
my-plugin-functions.php (5)
    Инициализация скриптов и стилей плагина и создание nonce’a для
                    верификации запроса в AJAX

function 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');
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');
}
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_a
function 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');
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_wp3
5', 'my_plugin_ajax_action_wp35');
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
        }
    });
});
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();
  };
}
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;
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
});
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_pl
ugin_action_wp35'},
      function(data) {
        if(data.res) {jQuery("#my-plugin-div").html(data.code);}
      }, "json");
});
custom_file_frame.open();
Спасибо за внимание!

  Вопросы

Mais conteúdo relacionado

Destaque

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Destaque (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

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

  • 1. Базовый плагин WordPress 1. Структура плагина 2. Работа с action’ами WordPress 3. Локаль в WordPress 4. Правильное подключение стилей и скриптов 5. AJAX в WordPress с помощью jQuery и JSON 6. Определение версии WordPress 7. Работа с API Media Uploader в зависимости от версии WordPress, втч новый Media Uploader
  • 3. my-plugin.php (1) Пока как-то так: /* Plugin Name: My Plugin Plugin URI: http://www.my-plugin.ru/ Description: My Plugin Description Author: Igor Sazonov Version: 1.0 Author URI: https://twitter.com/tigusigalpa */ include_once(plugin_dir_path(__FILE__).'/my-plugin-functions.php');
  • 4. my-plugin-functions.php (1) Определяем вспомогательные переменные $my_plugin_name = 'my-plugin';
  • 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. 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. 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. my-plugin-functions.php (4) Функция определения версии WordPress function my_plugin_get_wp_version() { global $wp_version; return $wp_version; }
  • 9. my-plugin-functions.php (5) Инициализация скриптов и стилей плагина и создание nonce’a для верификации запроса в AJAX function 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. 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. 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_a function 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. 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_wp3 5', 'my_plugin_ajax_action_wp35');
  • 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. 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. 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. 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. 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_pl ugin_action_wp35'}, function(data) { if(data.res) {jQuery("#my-plugin-div").html(data.code);} }, "json"); }); custom_file_frame.open();