• Сервис онлайн-записи на собственном Telegram-боте
    Тот, кто работает в сфере услуг, знает — без ведения записи клиентов никуда. Мало того, что нужно видеть свое расписание, но и напоминать клиентам о визитах тоже. Нашли самый бюджетный и оптимальный вариант: сервис VisitTime.
    Для новых пользователей первый месяц бесплатно.
    Чат-бот для мастеров и специалистов, который упрощает ведение записей:
    Сам записывает клиентов и напоминает им о визите;
    Персонализирует скидки, чаевые, кэшбэк и предоплаты;
    Увеличивает доходимость и помогает больше зарабатывать;
    Начать пользоваться сервисом
  • Как продвинуть сайт на первые места?
    Вы создали или только планируете создать свой сайт, но не знаете, как продвигать? Продвижение сайта – это не просто процесс, а целый комплекс мероприятий, направленных на увеличение его посещаемости и повышение его позиций в поисковых системах.
    Ускорение продвижения
    Если вам трудно попасть на первые места в поиске самостоятельно, попробуйте технологию Буст, она ускоряет продвижение в десятки раз, а первые результаты появляются уже в течение первых 7 дней. Если ни один запрос у вас не продвинется в Топ10 за месяц, то в SeoHammer за бустер вернут деньги.
    Начать продвижение сайта

Twenty Twelve: настраиваем стандартную тему wordpress. Часть 2

Здравствуйте, сегодня продолжим настраивать стандартную бесплатную wordpress тему – Twenty Twelve, а именно: вставим рекламу от Яндекса и Google AdSense внутри записей/постов, закруглим углы рамки и др.


Скачать исходники для статьи можно ниже

В нижеуказанной статье все изменения будут производиться над темой Twenty Twelve версии 1.8.

1. Закруглим рамки.

До изменений:

twenty twelve

После изменений:

twenty twelve

Достаточно добавить следующий код в файл стилей – style.css (админка – пункт “Внешний вид” – подпункт “Редактор” – справа в списке шаблонов выбрать файл style.css):

border-bottom: 5px solid #d5e6eb;
border-left: 5px solid #d5e6eb;
border-right: 5px solid #d5e6eb;
border-top: 5px solid #d5e6eb;
border-radius: 30px;

Вышеуказанный код нужно вставить в пункт:

/* Minimum width of 960 pixels. */
@media screen and (min-width: 960px)
...

Изначально данный пункт (“@media screen and (min-width: 960px)”) выглядит так:

/* Minimum width of 960 pixels. */
@media screen and (min-width: 960px) {
	body {
		background-color: #e6e6e6;
	}
	body .site {
		padding: 0 40px;
		padding: 0 2.857142857rem;
		margin-top: 48px;
		margin-top: 3.428571429rem;
		margin-bottom: 48px;
		margin-bottom: 3.428571429rem;
		box-shadow: 0 2px 6px rgba(100, 100, 100, 0.3);
	}
	body.custom-background-empty {
		background-color: #fff;
	}
	body.custom-background-empty .site,
	body.custom-background-white .site {
		padding: 0;
		margin-top: 0;
		margin-bottom: 0;
		box-shadow: none;
	}
}

Добавляем код закругления углов, после чего данный пункт (“@media screen and (min-width: 960px)”) будет выглядит так:

/* Minimum width of 960 pixels. */
@media screen and (min-width: 960px) {
	body {
		background-color: #e6e6e6;
	}
	body .site {
		padding: 0 40px;
		padding: 0 2.857142857rem;
		margin-top: 48px;
		margin-top: 3.428571429rem;
		margin-bottom: 48px;
		margin-bottom: 3.428571429rem;
		box-shadow: 0 2px 6px rgba(100, 100, 100, 0.3);
border-bottom: 5px solid #d5e6eb;
border-left: 5px solid #d5e6eb;
border-right: 5px solid #d5e6eb;
border-top: 5px solid #d5e6eb;
border-radius: 30px;
	}
	body.custom-background-empty {
		background-color: #fff;
	}
	body.custom-background-empty .site,
	body.custom-background-white .site {
		padding: 0;
		margin-top: 0;
		margin-bottom: 0;
		box-shadow: none;
	}
}

2. Добавляем фон на сайт в стиле Twitter:

После изменений:

twentytwelve6

Заходим в админке, в пункт “Внешний вид”, подпункта “Настроить”:

twenty twelve

Здесь заходим в пункт “Цвета” и устанавливаем цвет фона “#c0deed”:

twentytwelve4

Далее заходим в пункт “Фоновое изображение” и устанавливаем фоновый рисунок (можно скачать – здесь), а также параметры “Не повторять”, “Слева”, “Зафиксировать”:

twentytwelve5

3. Вставляем рекламу на сайте от Яндекса и Google Adsense.

Здесь просто расскажу как на моем сайте (тема Twenty Twelve) вставлена данная реклама.

Заходим в админку, выбираем пункт “Внешний вид”, подпункт “Редактор”, справа в списке шаблоновы выбираем файл – content.php.

За вывод контента в файле content.php – отвечает тег “php the_content”, вот его и будем заменять.

Находим в файле content.php следующую строчку:

<?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'twentytwelve' ) ); ?>

И меняем её на следующую конструкцию:

<?php if ( is_single() ) : ?>
Код рекламы
<?php else : ?>
<?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'twentytwelve' ) ); ?>
<?php endif; // is_single() ?>

Данной конструкцией мы задаем следующее – если (if) показывается запись (is_single), то показывать код рекламы, иначе (else) показывать стандартный код вывода контента. Делается это (условия if) для того, чтобы не нарушалась структура на главной странице сайта.

Теперь приведу код на своём сайте, который показывает рекламу Google Adsense после первого абзаца, выравненного слева, а также показ рекламы от Яндекса после 10 и 20 абзаца:

<?php if ( is_single() ) : ?>
<?php
$show_after_p = 1;
    $content = apply_filters('the_content', $post->post_content);
    if(substr_count($content, '<p>') > $show_after_p)
    {
        $contents = explode("</p>", $content);
        $p_count = 1;
        foreach($contents as $content)
        {
            echo $content;
if($p_count == 1)
{
?>
<br></br>
<strong>Скачать исходники для статьи можно ниже</strong>
<br></br>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- mnogoblog0 -->
<ins class="adsbygoogle"
     style="display:inline-block;width:300px;height:250px;float:left;margin-right:10px;"
     data-ad-client="ca-pub-7796639508090298"
     data-ad-slot="8518774317"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>

<?
}
if($p_count == 10)
{
?>
<!-- Яндекс.Директ -->
<script type="text/javascript">
//<![CDATA[
yandex_partner_id = 99180;
yandex_site_bg_color = 'FFFFFF';
yandex_site_charset = 'windows-1251';
yandex_ad_format = 'direct';
yandex_font_size = 1.2;
yandex_direct_type = 'flat';
yandex_direct_limit = 1;
yandex_stat_id = 8;
yandex_direct_title_font_size = 3;
yandex_direct_title_color = 'FF6600';
yandex_direct_url_color = '333333';
yandex_direct_text_color = '333333';
yandex_direct_hover_color = 'CC0000';
yandex_direct_favicon = true;
document.write('<sc'+'ript type="text/javascript" src="http://an.yandex.ru/system/context.js"></sc'+'ript>');
//]]>
</script>
<?
}
if($p_count == 20)
{
?>
<!-- Яндекс.Директ -->
<script type="text/javascript">
//<![CDATA[
yandex_partner_id = 99180;
yandex_site_bg_color = 'FFFFFF';
yandex_site_charset = 'windows-1251';
yandex_ad_format = 'direct';
yandex_font_size = 1.2;
yandex_direct_type = 'flat';
yandex_direct_limit = 1;
yandex_stat_id = 8;
yandex_direct_title_font_size = 3;
yandex_direct_title_color = 'FF6600';
yandex_direct_url_color = '333333';
yandex_direct_text_color = '333333';
yandex_direct_hover_color = 'CC0000';
yandex_direct_favicon = true;
document.write('<sc'+'ript type="text/javascript" src="http://an.yandex.ru/system/context.js"></sc'+'ript>');
//]]>
</script>
<?
}

echo "";
        $p_count++;
    }
}
?>
<?php else : ?>
<?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'twentytwelve' ) ); ?>
<?php endif; // is_single() ?>

Здесь – за обтекание рекламного блока от Google Adsense отвечает следующая строчка (просто добавлено к стандартному коду – обтекания слева и отступ справа):

style="display:inline-block;width:300px;height:250px;float:left;margin-right:10px;"

4. Добавляем в футере (подвале) сайта блок вывода последних комментариев.

Заходим в админке, в пункт “Внешний вид”, подпункт “Редактор”, справа в списке шаблонов выбираем пункт – footer.php и вставляем в него, в нужном вам месте, следующий код:

<div class="footer-recent-comments">
    <?php include (TEMPLATEPATH . '/simple_recent_comments.php'); ?>
	<?php if (function_exists('src_simple_recent_comments')) { src_simple_recent_comments(5, 60, '<h4>Последние комментарии</h4>', ''); } ?>
  </div>
  <!--recent comments end -->

Данный код подключает файл “simple_recent_comments.php”, который должен находится в папке текущей темы, то есть в папке “…\wp-content\themes\twentytwelve”.

Код данного файла должен быть следующим:

<?php
/*
Plugin Name: Simple Recent Comments
Plugin URI: 
Description: Shows a list of recent comments.
Version: 0.1.2
Author: 
Author URI: 
*/

/*
License: GPL
Compatibility: All

Installation:
Place the simple_recent_comments.php file in your /wp-content/plugins/ directory
and activate through the administration panel.

Usage:
This plugin returns an unordered list of the most recent comments.
It provides a template function you can use:
	src_simple_recent_comments(arg1, arg2, 'arg3', 'arg4')
Arguments explanation:
	arg1 (numeric): The number of comments to return. Default: 7
	arg2 (numeric): The comment excerpt length. Default: 60
	arg3 (alphanumeric): The HTML code to prepend to the list. Default: '<li><h2>Recent Comments</h2>'
	arg4 (alphanumeric): The HTML code to append to the list. Default: '</li>'

Of course it can be used without arguments. In this case the defaults will be used.
The default usage of the template function is to place it in the sidebar.
<?php src_simple_recent_comments(); ?>

I would recommend to use the following way of placing the function in your template:
	<?php if (function_exists('src_simple_recent_comments')) { src_simple_recent_comments(); } ?>
This way, even if you de-activate the plugin in your administration panel, but you
do not remove it from your templates, it would not produce any errors. The plugin simply will not
function at all and will show nothing.
*/

/*  Copyright (C) 
*/


/* Changelog
*/


function src_simple_recent_comments($src_count=7, $src_length=60, $pre_HTML='<li><h2>Recent Comments</h2>', $post_HTML='</li>') {
	global $wpdb;
	
	$sql = "SELECT DISTINCT ID, post_title, post_password, comment_ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type, 
			SUBSTRING(comment_content,1,$src_length) AS com_excerpt 
		FROM $wpdb->comments 
		LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) 
		WHERE comment_approved = '1' AND comment_type = '' AND post_password = '' 
		ORDER BY comment_date_gmt DESC 
		LIMIT $src_count";
	$comments = $wpdb->get_results($sql);

	$output = $pre_HTML;
	$output .= "\n<ul>";
	foreach ($comments as $comment) {
		$output .= "\n\t<li><strong><a href=\"" . get_permalink($comment->ID) . "#comment-" . $comment->comment_ID  . "\" title=\"on " . $comment->post_title . "\">" . $comment->comment_author . "</a></strong>: " . strip_tags($comment->com_excerpt) . "...</li>";
	}
	$output .= "\n</ul>";
	$output .= $post_HTML;
	
	echo $output;

}

?>

Скачать файл “simple_recent_comments.php” можно – здесь.

PS: Скачать тему Twenty Twelve версии 1.8. – можно здесь.

Добавить комментарий