Статья размещена автором Бетке Сергей Сергеевич

Пишем плагин для WordPress: часть 5, пишем в <head> блога

Выполним, наконец-то, первое полезное действие нашим плагином – выведем хотя-бы комментарий в head страниц блога, но не в консоль управления.

Как и обещал, приведу код плагина, который мы создали к этому моменту.

<?php 
/*
Plugin Name: COS Search provider
Plugin URI: http://sergey-s-betke.blogs.novgaro.ru/ie-search-provider-wordpress-plugin/
Description:This plugin add link teg for search descriptor.
Version: 1.0
Author: Sergey S. Betke
Author URI: http://sergey-s-betke.blogs.novgaro.ru/
License: GPL2

Copyright 2010 Sergey S. Betke (email : sergey.s.betke@novgaro.ru)

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

global $wp_version;
if ( version_compare($wp_version, "3.0", "<") ) {
   $pluginError = sprintf(__('COS Search Provider requires WordPress %s or newer. <a href="http://codex.wordpress.org/Upgrading_WordPress">Please update!</a>'));
   exit ($pluginError);
}

register_activation_hook    ( __FILE__, array('cos_search_provider', 'activation'        ));
register_deactivation_hook  ( __FILE__, array('cos_search_provider', 'deactivation'      ));
register_uninstall_hook     ( __FILE__, array('cos_search_provider', 'uninstall'         ));

add_action('plugins_loaded', array('cos_search_provider', 'plugins_loaded'));

class cos_search_provider {

   private static $_name;
   private static $_namespace = __CLASS__;
   private static $_folder;
   private static $_domain;
   private static $_path;
   private static $_link = 'http://sergey-s-betke.blogs.novgaro.ru/ie-search-provider-wordpress-plugin/';
   private static $options;
   
   public static function activation() {
   }

   public static function deactivation() {
      unregister_setting(
         self::$_namespace,
         self::$_namespace . '_options',
         array(__CLASS__, 'validate_options')
      );
   }

   public static function uninstall() {
      delete_option(self::$_namespace . '_options');
   }

   public static function plugins_loaded() {
      self::$_folder = dirname(plugin_basename(__FILE__));
      self::$_domain = self::$_folder;
      self::$_path = WP_PLUGIN_DIR . '/' . self::$_folder . '/';

      load_plugin_textdomain(self::$_domain, false, self::$_folder . '/languages/');
      self::$_name = __('COS Search provider', self::$_domain);
      self::$options = self::validate_options(get_option(self::$_namespace . '_options'));

      add_action('admin_init', array(__CLASS__, 'admin_init'));
      add_action('admin_menu', array(__CLASS__, 'admin_menu'));

      add_action('wp_head',    array(__CLASS__, 'wp_head'   ));
   }
   
   public static function admin_init() {
      register_setting(
         self::$_namespace,
         self::$_namespace . '_options',
         array(__CLASS__, 'validate_options')
      );
      add_settings_section(
         self::$_namespace . '_main_options',
         __('Main Settings', self::$_domain),
         false,
         self::$_namespace . '_options_page'
      );
      add_settings_field(
         self::$_namespace . '_options[title]',
         __('Title', self::$_domain),
         array(__CLASS__, 'option_control_title'),
         self::$_namespace . '_options_page',
         self::$_namespace . '_main_options'
      );
   }

   public static function option_control_title() {
      ?>      
          <input
            name="<?php echo self::$_namespace . '_options[title]' ?>"
            type="text"
            size="50"
            value="<?php echo self::$options['title']; ?>"
          />
      <?php      
   }
   
   public static function validate_options($options) {
      if (!is_array($options)) {
         $options = array(
            'title' => get_bloginfo('name')
         );
      }

      if ($options['title'] == '') $options['title'] = get_bloginfo('name');
  
      return $options;
   }
   
   public static function admin_menu() {
      add_options_page(
         __('COS search provider options', self::$_domain)
         , self::$_name
         , 'manage_options'
         , self::$_namespace . '_options_page'
         , array(__CLASS__, 'options_page')
      );
   }

   public static function options_page() {
      ?>      
      <div class="wrap">
      <?php screen_icon('options-general'); ?>
      <h2><?php _e('COS search provider options', self::$_domain) ?></h2>
      <form method="post" action="options.php">
         <?php
            settings_fields(self::$_namespace);
            self::$options = self::validate_options(get_option(self::$_namespace . '_options'));
            do_settings_sections(self::$_namespace . '_options_page');
         ?> 
      <p class="submit">
        <input name="Submit" type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" />
      </p>
      </form>
      </div>
      <?php      
   }

   public static function wp_head() {
      ?>
<!-- xxxx<?php echo self::$options['title']; ?>yyyy -->
      <?php
   }
   
}
?>

Для начала дам одну полезную ссылку – перечень событий wordpress 3.0. Хорошо видно, что за формирование заголовков страниц блога (между тегами head) отвечает событие wp_head и его обработчики, за формирование заголовков страниц консоли управления wordpress – событие admin_head. Поэтому для решения поставленной задачи достаточно повесить обработчик события wp_head. Итак, необходимые дополнения в коде выделены.

Опубликовать комментарий

XHTML: Вы можете использовать следующие HTML теги: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Tags Связь с комментариями статьи:
RSS комментарии
Обратная ссылка