Давайте посмотрим, как мы можем сделать очень простой плагин, показывающий некоторые последние сообщения из учетной записи Twitter.
Шаг 1 Скачать скрипты
Прежде чем мы начнем писать наш плагин, нам нужно немного кода JavaScript.
Шаг 2 Создание файловой структуры и копирование файлов
Создайте этот каталог: / wp-content / plugins / tweetfeed-light , а затем скопируйте эти файлы.
|
01
02
03
04
05
06
07
08
09
10
11
12
|
/css
style.css
/img
buttons.png
interface.png
interface_dark.png
twitter_bird.png
/js
jquery.tweetable.min.js
jquery-1.7.2.min.js
|
Шаг 3 Основные данные плагина
Продолжайте создавать tweetfeed-light.php (имя нашего основного файла плагина) с указанным ниже содержимым.
|
1
2
3
4
5
6
7
8
|
/*
Plugin Name: Tweetfeed Light
Plugin URI: http://wp.tutsplus.com
Description: Show latest Tweets in sidebar for a given Twitter user
Version: 1.0
Author: Adam Burucs
Author URI: http://wp.tutsplus.com
*/
|
Шаг 4 Плагин Класс
Основная декларация нашего класса плагинов.
|
1
2
|
class AB_Tweetfeed_Light {
}
|
Шаг 5 Функция конструктора
Это хорошая идея, чтобы поместить в эту функцию начальные настройки и требования. В этом разделе мы устанавливаем следующее:
- путь к плагину
- короткий код
- импорт скриптов
- импорт стилей
Код для этих задач:
|
01
02
03
04
05
06
07
08
09
10
11
12
13
|
public function __construct() {
// set plugin path
$this->pluginUrl = WP_PLUGIN_URL .
// set shortcode
add_shortcode(‘tweetfeed-light’, array($this, ‘shortcode’));
// import scripts
wp_enqueue_script(‘tweetable-script’, $this->pluginUrl . ‘/js/jquery.tweetable.min.js’, array( ‘jquery’ ));
// import style
wp_enqueue_style(‘tweetable-style’, $this->pluginUrl . ‘/css/style.css’);
}
|
Шаг 6 Получение твитов
Получите последние твиты от пользователя. Мы также можем установить предельную переменную, управляющую количеством твитов.
|
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
|
public function loadTweets($user, $limit) {
// render tweets to div element
echo ‘<div id=»tweets»></div>’;
// render javascript code to do the magic
echo
‘<script type=»text/javascript»>
jQuery(function(){
jQuery(«#tweets»).tweetable({
username: «‘ . $user . ‘»,
limit: ‘ .
replies: true,
position: «append»});
});
</script>’;
}
|
Шаг 7 Функция шорткода
Это вспомогательный скрипт для использования плагина с шорткодом.
|
1
2
3
4
|
// render tweets with shortcode
public function shortcode($data) {
return $this->loadTweets($data[‘username’]);
}
|
Шаг 8 Учебный класс
Сделайте объект из класса плагина.
|
1
2
|
// run plugin
$tweetfeed_light = new AB_Tweetfeed_Light();
|
Шаг 9 Окончательный код
Вот как выглядит код, когда он закончен.
|
01
02
03
04
05
06
07
08
09
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
|
/*
Plugin Name: Tweetfeed Light
Plugin URI: http://wp.tutsplus.com
Description: Show latest Tweets in sidebar for a given Twitter user
Version: 1.0
Author: Adam Burucs
Author URI: http://wp.tutsplus.com
*/
class AB_Tweetfeed_light {
public function __construct() {
// set plugin path
$this->pluginUrl = WP_PLUGIN_URL .
// set shortcode
add_shortcode(‘tweetfeed-light’, array($this, ‘shortcode’));
// import scripts
wp_enqueue_script(‘tweetable-script’, $this->pluginUrl . ‘/js/jquery.tweetable.min.js’, array( ‘jquery’ ));
// import style
wp_enqueue_style(‘tweetable-style’, $this->pluginUrl . ‘/css/style.css’);
}
public function loadTweets($user, $limit) {
// render tweets to div element
echo ‘<div id=»tweets»></div>’;
// render javascript code to do the magic
echo
‘<script type=»text/javascript»>
jQuery(function(){
jQuery(«#tweets»).tweetable({
username: «‘ . $user . ‘»,
limit: ‘ .
replies: true,
position: «append»});
});
</script>’;
}
// render tweets with shortcode
public function shortcode($data) {
return $this->loadTweets($data[‘user’], $data[‘limit’]);
}
}
// run plugin
$tweetfeed_light = new AB_Tweetfeed_Light();
|
Шаг 10 Использование шорткода
Чтобы использовать этот плагин, вы можете написать [tweetfeed-light user="johnb" limit="10"] нужный вам источник страницы. Например:
|
1
2
3
4
5
|
…
<div class=»menu»>…</div>
[tweetfeed-light user=»johnb» limit=»10″]
<div class=»footer»>…</div>
…
|
Шаг 11 Взгляд
Вот как выглядит плагин в стандартной теме WordPress, вставленной в объект страницы.
Резюме
Как видите, это простое, но отличное решение для нашей мини-миссии Twitter. Для дальнейшей (цветной) настройки вы должны заглянуть во включенную таблицу стилей. Спасибо Icontexto за фотографию в Твиттере!
