<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Блог GTAlex - о работе в сети и не только &#187; плагин</title>
	<atom:link href="http://gtalex.ru/tag/plagin/feed" rel="self" type="application/rss+xml" />
	<link>http://gtalex.ru</link>
	<description>SEO, Яндекс, Google, PHP, Apache, nginx, CMS, создание, взлом и защита сайтов...</description>
	<lastBuildDate>Wed, 01 Feb 2012 10:05:05 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=abc</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>Плагин Wordpress своими руками</title>
		<link>http://gtalex.ru/plagin-wordpress-svoimi-rukami</link>
		<comments>http://gtalex.ru/plagin-wordpress-svoimi-rukami#comments</comments>
		<pubDate>Thu, 06 Aug 2009 06:35:20 +0000</pubDate>
		<dc:creator>GTAlex</dc:creator>
				<category><![CDATA[CMS]]></category>
		<category><![CDATA[Новости / Обзоры]]></category>
		<category><![CDATA[Полезности]]></category>
		<category><![CDATA[Программирование]]></category>
		<category><![CDATA[Размышления]]></category>
		<category><![CDATA[плагин]]></category>

		<guid isPermaLink="false">http://blog.gtalex.ru/?p=636</guid>
		<description><![CDATA[ Решил уже добить своё детище Always Last&#160;&#8212; примочка к WP, добавлящая последний комментарий с заданным содержимым&#160;&#8212; в моем случае содержимое&#160;&#8212; это 3 самые обсуждаемые темы на блогах в рунете (это дело конечно же грабится из Яндекс Блогов).
Как это было сделано раньше (тут можно и без критики&#160;&#8212; делалось на коленке &#171;лишь бы работало&#187;)
wp-comments-post.php
перед последней строчкой [...]]]></description>
			<content:encoded><![CDATA[<p> Решил уже добить своё детище Always Last&nbsp;&mdash; примочка к WP, добавлящая последний комментарий с заданным содержимым&nbsp;&mdash; в моем случае содержимое&nbsp;&mdash; это 3 самые обсуждаемые темы на блогах в рунете (это дело конечно же грабится из Яндекс Блогов).</p>
<p>Как это было сделано раньше (тут можно и без критики&nbsp;&mdash; делалось на коленке &laquo;лишь бы работало&raquo;)</p>
<p><strong>wp-comments-post.php</strong></p>
<p>перед последней строчкой wp_redirect($location); уже после обработки добавления обычного комментария, добавил добавление своего</p>
<blockquote>
<p>$comment_author       = &#39;Always last&#39;;<br />
$comment_author_email = &#39;lasted@yandex.ru&#39;;<br />
$comment_author_url   = &#39;http://blog.gtalex.ru/&#39;;<br />
//$comment_content = iconv(&laquo;WINDOWS-1251&raquo;, &laquo;UTF-8&raquo;, &laquo;Самое обсуждаемое на блогах:\n&raquo;);<br />
$comment_content = &#39;Самое обсуждаемое на блогах:&#39;;</p>
<p>$cashe = @file(&#39;top3.cashe&#39;);<br />
list($time, $ids, $themes) = unserialize($cashe[0]);<br />
foreach($themes as $theme) {<br />
//    $comment_content.= iconv(&laquo;WINDOWS-1251&raquo;, &laquo;UTF-8&raquo;, $theme."\n");<br />
$comment_content.= &#39;&lt;br/&gt;&#39;.$theme;<br />
}</p>
<p>$commentdata = compact(&#39;comment_post_ID&#39;, &#39;comment_author&#39;, &#39;comment_author_email&#39;, &#39;comment_author_url&#39;, &#39;comment_content&#39;, &#39;comment_type&#39;, &#39;user_ID&#39;);</p>
<p>$comment_id = wp_my_comment( $commentdata );</p>
</blockquote>
<p><strong>wp-includes\comment.php</strong></p>
<p>сюда добавил функцию непосредственно добавляющую комментарий</p>
<blockquote>
<p>function wp_my_comment( $commentdata ) {</p>
<p>global $wpdb;</p>
<p>$commentdata['comment_post_ID'] = (int) $commentdata['comment_post_ID'];<br />
$comment_post_ID = $commentdata['comment_post_ID'];<br />
$commentdata['user_ID']         = (int) $commentdata['user_ID'];</p>
<p>// если в комментариях уже был комментарий от  &#39;Always last&#39;&nbsp;&mdash; удаляем<br />
$id = $wpdb-&gt;get_var(&laquo;SELECT comment_ID FROM $wpdb-&gt;comments WHERE comment_post_ID = &#39;$comment_post_ID&#39; and comment_author = &#39;Always last&#39; LIMIT 1&raquo;);</p>
<p>if ($id&gt;1) {<br />
wp_delete_comment($id);<br />
}</p>
<p>sleep(1);</p>
<p>$commentdata['comment_author_IP'] = preg_replace( &#39;/[^0-9., ]/&#39;, &#39;&#39;,$_SERVER['REMOTE_ADDR'] );<br />
$commentdata['comment_agent']     = $_SERVER['HTTP_USER_AGENT'];</p>
<p>//    $commentdata['comment_agent']     = $id;</p>
<p>$commentdata['comment_date']     = current_time(&#39;mysql&#39;);<br />
$commentdata['comment_date_gmt'] = current_time(&#39;mysql&#39;, 1);</p>
<p>$comment_ID = wp_insert_comment($commentdata);<br />
return $comment_ID;<br />
}</p>
</blockquote>
<p>Вроде всё ничего&nbsp;&mdash; работает и ладно, НО, как вы наверное уже обратили внимание на исправляемые файлы&nbsp;&mdash; при каждом обновлении движка WP приходится эти блоки вставлять заново&nbsp;&mdash; неудобно и не профессионально.</p>
<p>В общем решил я оформить это дело в виде плагина (эх страшно даже).</p>
<p>Во первых я решил убрать прямую работу с базой&nbsp;&mdash; вставка комментария, удаление и т.д. Краткость&nbsp;&mdash; сестра таланта, да и побыстрее будет работать. <img src='http://gtalex.ru/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  Просто берем содержимое файла и в момент вывода странички с комментариями, выводим последним.</p>
<p>Плагин получился до безобразия простой и что удивительно&nbsp;&mdash; рабочий (с первого раза завелся).</p>
<p>Вот непосредственно код файла AlwaysLast.php</p>
<blockquote>
<p>&lt;?php<br />
/*<br />
Plugin Name: Always Last<br />
Plugin URI: http://blog.gtalex.ru<br />
Description: Insert Always Last comment<br />
Version: 1.0.0<br />
Author: GTAlex<br />
Author URI: http://blog.gtalex.ru<br />
*/</p>
<p>/*  Copyright 2009  GTAlex  (email : anubis3d@gmail.com)</p>
<p>This program is free software; you can redistribute it and/or modify<br />
it under the terms of the GNU General Public License as published by<br />
the Free Software Foundation; either version 2 of the License, or<br />
(at your option) any later version.</p>
<p>This program is distributed in the hope that it will be useful,<br />
but WITHOUT ANY WARRANTY; without even the implied warranty of<br />
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the<br />
GNU General Public License for more details.</p>
<p>You should have received a copy of the GNU General Public License<br />
along with this program; if not, write to the Free Software<br />
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110&mdash;1301  USA<br />
*/</p>
<p>function GT_AlwaysLast ()<br />
{<br />
$comment_content = &#39;Самое обсуждаемое на блогах:&#39;;</p>
<p>$cashe = @file(&#39;top3.cashe&#39;);<br />
list($time, $ids, $themes) = unserialize($cashe[0]);<br />
foreach($themes as $theme) {<br />
//    $comment_content.= iconv(&laquo;WINDOWS-1251&raquo;, &laquo;UTF-8&raquo;, $theme."\n");<br />
$comment_content.= &#39;&lt;br/&gt;&#39;.$theme;<br />
}<br />
echo &laquo;&lt;li&gt; &lt;cite&gt; Always Last &lt;/cite&gt; said:\n&raquo;;<br />
echo &laquo;&lt;blockquote&gt;&raquo;.$comment_content."&lt;/blockquote&gt;&lt;/li&gt;\n";<br />
return true;<br />
}<br />
?&gt;</p>
</blockquote>
<p>В плагине подрубаем функцию выводящую нужный комментарий. Закидываем получившийся файлик в папку с плагинами (желательно под плагин тоже создать папочку). Из панели управления активируем плагин.</p>
<p>Для того чтоб заработало, ещё необходимо подправить  файлик <strong>wp-content\themes\Ваша Тема\comments.php</strong></p>
<p>После строчки</p>
<blockquote>
<p>&lt;?php endforeach; /* end for each comment */ ?&gt;</p>
</blockquote>
<p>Добавляем вызов нашей функции</p>
<blockquote>
<p>&lt;?php if ( function_exists(&#39;GT_AlwaysLast&#39;) ) GT_AlwaysLast(); ?&gt;</p>
</blockquote>
<p>Вуаля&nbsp;&mdash; Готово!</p>
<p>Результат работы плагина можно увидеть в любом посте&nbsp;&mdash; последний комментарий будет от Always Last.</p>
<p>При написании плагина и сего поста были использованы следующие материалы (если есть желание сваять плагинчик&nbsp;&mdash; очень советую всё изучить&nbsp;&mdash; изложено наглядно и понятно).</p>
<p><a href="http://jenyay.net/Programming/WPPlugins1" target="_blank">Делаем плагины для WordPress. Часть 1</a></p>
<p><a href="http://jenyay.net/Programming/WPPlugins2" target="_blank">Делаем плагины для WordPress. Часть 2<br />
</a></p>
<p><a href="http://jenyay.net/Programming/WPPlugins3" target="_blank">Делаем плагины для WordPress. Часть 3</a></p>
<p>P.S.</p>
<p>При наличии времени нужно будет довести плагинчик до ума&nbsp;&mdash; во первых сделать, чтоб не приходилось в ручную править comments.php, а во вторых сделать настройку для плагина, где можно было бы редактировать Юзера, от которого идет комментарий и непосредственно Текст сообщения. Как такое сделать, опять же, подробно расписано в вышеупомянутых статьях.</p>
<p>У меня берется из файла&nbsp;&mdash; т.к. именно в него я сохраняю результат парсинга Я.Блоги.</p>
<p>Дальнейшее обсуждение, новые версии и пр. перенесено на форум в одноименную ветку<br />
<a href="http://forum.gtalex.ru/index.php?topic=17.0">Wordpress своими руками</a></p>
<p><center>&copy; <a href="http://blog.gtalex.ru/"> Блог GTAlex </a> - деньги из паутины </center></p>
<p align="center"><a target="_blank" class="tt" href="http://twitter.com/home/?status=%D0%9F%D0%BB%D0%B0%D0%B3%D0%B8%D0%BD+Wordpress+%D1%81%D0%B2%D0%BE%D0%B8%D0%BC%D0%B8+%D1%80%D1%83%D0%BA%D0%B0%D0%BC%D0%B8+http://tinyurl.com/6ybsu5g" title="Post to Twitter"><img class="nothumb" src="http://gtalex.ru/wp-content/plugins/tweet-this/icons/tt-twitter.png" alt="Post to Twitter" /></a> <a target="_blank" class="tt" href="http://twitter.com/home/?status=%D0%9F%D0%BB%D0%B0%D0%B3%D0%B8%D0%BD+Wordpress+%D1%81%D0%B2%D0%BE%D0%B8%D0%BC%D0%B8+%D1%80%D1%83%D0%BA%D0%B0%D0%BC%D0%B8+http://tinyurl.com/6ybsu5g" title="Post to Twitter">ReTweet</a></p>
]]></content:encoded>
			<wfw:commentRss>http://gtalex.ru/plagin-wordpress-svoimi-rukami/feed</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
	</channel>
</rss>

