Делаем динамический заголовок страницы
Если вы — разработчик тем WordPress и вам нужно динамически изменять заголовок страницы, то этот сниппет для вас.
Необходимо добавить код в файл functions.php вашей темы:
function page_title() {
<div style="float:right;width:350px;margin:0 0 10px 15px;">
<div id="yandex_rtb_R-A-187781-2"></div>
</div>
if (is_home()) {
_e('Home', 'theme');
} elseif (is_archive()) {
$term = get_term_by('slug', get_query_var('term'), get_query_var('taxonomy'));
if ($term) {
echo $term->name;
} elseif (is_post_type_archive()) {
echo get_queried_object()->labels->name;
} elseif (is_day()) {
printf(__('Daily Archives: %s', 'theme'), get_the_date());
} elseif (is_month()) {
printf(__('Monthly Archives: %s', 'theme'), get_the_date('F Y'));
} elseif (is_year()) {
printf(__('Yearly Archives: %s', 'theme'), get_the_date('Y'));
} elseif (is_author()) {
global $post;
$author_id = $post->post_author;
printf(__('Author Archives: %s', 'theme'), get_the_author_meta('display_name', $author_id));
} else {
single_cat_title();
}
} elseif (is_search()) {
printf(__('Search Results for %s', 'theme'), get_search_query());
} elseif (is_404()) {
_e('File Not Found', 'theme');
} else {
the_title();
}
}
Добавляем код Google Analytics без плагинов
Следующий сниппет позволяет с помощью функции вставить код Google Analytics в тему (код выведется в футере страниц):
add_action('wp_footer', 'add_google_analytics');
function add_google_analytics() {
?>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-XXXXXXX-X");
pageTracker._trackPageview();
} catch(err) {}</script>
<?php
}
Собственная Favicon для WP-Admin
Следующий сниппет позволяет добавить фавикон к админке сайта. Саму фавиконку кладем в папку с темой, в подпапку /images/favicon.ico. Путь конечно же можно подправить на свой.
function admin_favicon() {
echo ' <link href="' . get_bloginfo('template_directory') . '/images/favicon.ico" rel="shortcut icon" type="image/x-icon" />';
}
add_action( 'admin_head', 'admin_favicon' );
Убираем колонку комментариев в списке постов админки
Сниппет добавляем в файл functions.php вашей темы:
add_filter('manage_pages_columns', 'custom_pages_columns');
function custom_pages_columns($defaults) {
unset($defaults['comments']);
return $defaults;
}
Подсветка искомого слова в результатах поиска
Для удобства пользователей можно подсвечивать ту фразу в результатах поиска, которую запрашивал пользователь. Для этого для начала нужно добавить код в файл functions.php вашей темы:
add_filter('the_content', 'highlight_search_text', 99);
add_filter('the_title', 'highlight_search_text', 99);
function highlight_search_text($title) {
if(is_search()) {
$keys= explode(" ",get_search_query());
return preg_replace('/('.implode('|', $keys) .')/iu','<strong class="search-excerpt">\0</strong>',$title);
}
return $title;
}
Затем добавляем немного css кода в файл style.css темы:
Add following css style to your “style.css”
strong.search-excerpt { background: yellow; }
Результат поиска по запросу “Hello”:
![search-highlight1[1]](http://wpincode.com/wp-content/uploads/2014/01/search-highlight11.jpg)
Добавляем дополнительное поле в форму комментариев
Допустим, вам необходимо добавить дополнительное поле «location» в форму комментариев.
Для этого добавляем следующий код в файл functions.php вашей темы:
add_filter( 'comment_form_defaults', 'add_extra_comment_form_field'); // Выводим поле
add_filter( 'preprocess_comment', 'verify_comment_meta_data' ); // Проверяем данные
add_action( 'comment_post', 'save_comment_meta_data' );
add_filter( 'get_comment_author_link', 'attach_location_to_author' ); // Получаем и отображаем данные
// Выводим поле
function add_extra_comment_form_field( $default ) {
$commenter = wp_get_current_commenter();
$default[ 'fields' ][ 'email' ] .= '<p class="comment-form-author">' .
'<label for="Location">'. __('Location') . '</label>
<span class="required">*</span>
<input id="location" name="location" size="30" type="text" /></p>';
return $default;
}
// Проверяем данные
function verify_comment_meta_data( $commentdata ) {
if ( ! isset( $_POST['location'] ) )
wp_die( __( 'Error: please fill the required field (location).' ) );
return $commentdata;
}
//Получаем и отображаем данные
function save_comment_meta_data( $comment_id ) {
add_comment_meta( $comment_id, 'location', $_POST[ 'location' ] );
}
//Получаем и отображаем данные
function attach_location_to_author( $author ) {
$city = get_comment_meta( get_comment_ID(), 'location', true );
if ( $location)
$author .= " ($location)";
return $author;
}
Результат будет примерно следующий:
![comment-form-extra-field[1]](http://wpincode.com/wp-content/uploads/2014/01/comment-form-extra-field1.jpg)
Естественно, поле location указано в качестве примера. Добавить вы вольны всё, что угодно.
