На этой странице представлено собрание сниппетов для популярной CMS WordPress. Много других сниппетов для WordPress вы найдёте в статьях сайта. Для быстрого поиска перейдите на страницу "Карта сайта".
robots.txt
User-Agent: Yandex
Allow: /wp-content/uploads/
Disallow: /wp-login.php
Disallow: /wp-register.php
Disallow: /xmlrpc.php
Disallow: /template.html
Disallow: /wp-admin
Disallow: /wp-includes
Disallow: /wp-content
Disallow: /tag
Disallow: /category
Disallow: /archive
Disallow: */trackback/
Disallow: */feed/
Disallow: */comments/
Disallow: /?feed=
Disallow: /?s=
User-Agent: *
Allow: /wp-content/uploads/
Disallow: /wp-login.php
Disallow: /wp-register.php
Disallow: /xmlrpc.php
Disallow: /template.html
Disallow: /wp-admin
Disallow: /wp-includes
Disallow: /wp-content
Disallow: /tag
Disallow: /category
Disallow: /archive
Disallow: */trackback/
Disallow: */feed/
Disallow: */comments/
Disallow: /?feed=
Disallow: /?s=
Sitemap: http://site.ru/sitemap.xmlGoogle: https://support.google.com/webmasters/answer/6062598
Яндекс: https://yandex.ru/support/webmaster/indexing-options/robots-txt-analyzer.html
или:
User-agent: Yandex
Disallow: /wp-admin
Disallow: /wp-includes
Disallow: /wp-content/plugins
Disallow: /wp-json/
Disallow: /wp-login.php
Disallow: /wp-register.php
Disallow: */embed
Disallow: */page/
Disallow: /cgi-bin
Disallow: *?s=
Allow: /wp-admin/admin-ajax.php
Host: site.ru
User-agent: *
Disallow: /wp-admin
Disallow: /wp-includes
Disallow: /wp-content/plugins
Disallow: /wp-json/
Disallow: /wp-login.php
Disallow: /wp-register.php
Disallow: */embed
Disallow: */page/
Disallow: /cgi-bin
Disallow: *?s=
Allow: /wp-admin/admin-ajax.php
Sitemap: http://example.com/sitemap.xmlПлагин formember
Позволяет добавлять на страницу некоторое содержимое, которое будет доступно только зарегистрированным посетителям. Выводится такое содержимое с помощью шоркода: [formember]...[/formember]
<?php
/*
Plugin Name: formember
...
*/
// [formember] отображаемое содержимое [/formember]
function member_check($atts, $content = null) {
if (is_user_logged_in() && !is_null($content) && !is_feed()) {
return $content; // отображаемое содержимое
} else {
return 'Только для зарегистрированных посетителей';
}
}
add_shortcode('formember', 'member_check');
?>Пользовательский шоркод
function functionsphp_shortcode_custom ( $atts , $content = null ) {
return '<div class="">'. do_shortcode( $content ) .'</div>';
}
add_shortcode( 'custom', 'functionsphp_shortcode_custom' );Будет добавлен шоркод custom, содержимое которое заключено в div с каким-либо классом.
Пример шорткода
function tbare_wordpress_plugin_demo($atts) {
$Content = "<style>\r\n";
$Content .= "h3.demoClass {\r\n";
$Content .= "color: #26b158;\r\n";
$Content .= "}\r\n";
$Content .= "</style>\r\n";
$Content .= '<h3 class="demoClass">Check it out!</h3>';
return $Content;
}
add_shortcode('tbare-plugin-demo', 'tbare_wordpress_plugin_demo');[tbare-plugin-demo]
Вставить шоркод в PHP
<?php echo do_shortcode('[имя шорткода]'); ?>Как перенести сайт на локальный сервер
Способ первый
- Поместить папку wp-content в директорию вордпресс, установленном на локальном сервере.
- Создать новую базу данных
- Сделать SQL-запрос:
UPDATE wp_options SET option_value = replace(option_value, 'http://www.example.com', 'http://localhost/test-site') WHERE option_name = 'home' OR option_name = 'siteurl';
UPDATE wp_posts SET post_content = replace(post_content, 'http://www.example.com', 'http://localhost/test-site');
UPDATE wp_postmeta SET meta_value = replace(meta_value,'http://www.example.com','http://localhost/test-site');Для Open Server:
UPDATE wp_options SET option_value = replace(option_value, 'http://www.example.com', 'http://test-site') WHERE option_name = 'home' OR option_name = 'siteurl';
UPDATE wp_posts SET post_content = replace(post_content, 'http://www.example.com', 'http://test-site');
UPDATE wp_postmeta SET meta_value = replace(meta_value,'http://www.example.com','http://test-site');Способ второй
Для переноса сайта на другой хостинг, с локального сервера или на локальный сервер можно использовать плагин Duplicator
Инструменты для замены ссылок в базе данных: Better Search Replace Search-Replace-DB
Как перенести сайт с локального сервера на хостинг
- Отредактировать wp-config.php.
- Импортировать базу данных.
- Открыть таблицу wp_options и изменить строчки siteurl и home, заменив имеющийся адрес, на адрес нового сайта без слеша в конце.
- Установить плагин Velvet Blues Update URLs и обновить ссылки
Добавление svg в перечень MIME-типов WordPress
Для того, чтобы снять запрет на загрузку svg файлов в медиабиблиотеку, прописать в functions.php:
function cc_mime_types( $mimes ){
$mimes['svg'] = 'image/svg+xml';
return $mimes;
}
add_filter( 'upload_mimes', 'cc_mime_types' );Генератор ключей безопасности
Нет нужды сохранять ссылку в закладках на генератор ключей безопасности, которые потребуются при установке WordPress — ссылка на генератор есть в самом файле конфигурации wp-config.php, где эти ключи прописываются. Если открыть файл, например, в Notepad++, ссылка будет активной.
Скрыть часть страницы от не авторизованных пользователей
В файл functions.php:
add_shortcode('swp_logged_in', 'swp_if_logged_in');
function swp_if_logged_in($atts, $content=""){
if ( is_user_logged_in() ) {
return $content;
}else{
return '<div class="swp_no_logged_in_msg">Для просмотра необходимо авторизоваться.</div>';
}
}На страницу в которой хотим что-то скрыть и в режиме кода ставим [swp_logged_in] перед нужной нам частью страницы и [/swp_logged_in] после этой части.
Второй вариант:
function true_logged_in_user_content( $atts, $content = null ) {
if ( is_user_logged_in() && !is_null( $content ) && !is_feed() ) {
return $content;
}
return ''; // тут в кавычках можете написать сообщение об ошибке, отображающееся для пользователей, у которых нет доступа, можно использовать HTML.
}
add_shortcode( 'member', 'true_logged_in_user_content' );При написании поста, когда вы захотите скрыть какую-то часть текста, просто поместите его между .
Третий вариант:
function true_content_by_user_cap( $attr, $content = null ) {
// массив со значениями по умолчанию, которые будут применяться, если в шорткоде не был указан параметр
$defaults = array(
'capability' => 'read'
);
extract( shortcode_atts( $defaults, $attr ) );
if ( current_user_can( $capability ) && !is_null( $content ) && !is_feed() ) {
return $content;
}
return ''; // указываем сообщение об ошибке если нужно
}
add_shortcode( 'access', 'true_content_by_user_cap' );Сам шорткод на странице редактирования поста будет выглядеть следующим образом:
[access capability="edit_posts"]
Эта часть контента видна пользователям, которые могут редактировать записи.
[/access]
А в этом случае будут применяться значения по умолчанию из массива $defaults:[access]
Это сообщение увидят все зарегистрированные пользователи.
[/access]
Скрытие контента который находится в шорт коде (то есть необходимо скрыть содержимое шорткода например [hide_content_shortcode] [ШОРТ КОД КОНТЕНТ КОТОРОГО НЕОБХОДИМО СКРЫТЬ] [/hide_content_shortcode]) от не зарегистрированных посетителей при помощи шорт кодов[hide_content_shortcode] перед контентом, который необходимо скрыть, и [/hide_content_shortcode] после.
/* Теперь добавим шорткод [hide_content_shortcode] перед контентом, который необходимо скрыть, и [/hide_content_shortcode] после */
function hidden_content_from_guests( $atts, $content = null ) {
if (is_user_logged_in() && !is_null($content) && !is_feed()) {
return do_shortcode($content);
}
return '<span><p class="aligncenter">Контент доступен только для зарегистрированных пользователей!</br>Пожалуйста <a href="#" style="color: #3d8e22;">зарегистрируйтесь</a> или <a href="#" style="color: #3d8e22;">авторизируйтесь</a></p></span>';
}
add_shortcode( 'hide_content_shortcode', 'hidden_content_from_guests' );
/* END */Вывод рейтинга
Внутри цикла:
<?php while (have_posts()) : the_post(); ?> /* Вставить здесь */ <?php endwhile; ?>
Поместить строчку:
<?php if(function_exists('the_ratings')) { the_ratings(); } ?>Руссифицировал последнюю версию (1.81):
[ Скачать ]
"Хлебные крошки" (только на страницах записей)
В файле single.php (можно открыть во "Внешний вид" → "Редактор") после строки:
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
Вставляем следующий код:
<div id="breadcrumbs">
<?php if (is_home()) { ?>
<?php } elseif (is_single()) { ?>
<a href="<?php echo get_option('home'); ?>">Главная</a> »
<?php foreach((get_the_category()) as $cat) {
$cat=$cat->cat_ID;
echo(get_category_parents($cat, TRUE, ' » ')); } the_title(); ?>
<?php } ?>
</div>Во "Внешний вид" → "Редактор" - "styles.css" вставляем стили для навигации:
/* Стили для хлебных крошек */
#breadcrumbs {
width: auto; /* Общая ширина страницы */
font-size: 14px; /* Размер шрифта */
color: #215B9B; /* Цвет текста, который не является ссылкой */
text-shadow: #5DB6FA 0px 1px 1px; /* Тени для текста (необязательно) */
text-align: left; /* Прижимаем текст к левому краю страницы */
margin: 3px 30px 0px 30px; /* Внешние отступы */
padding-bottom: 5px; /* Внутренние отступы */
border-bottom: 2px solid #f2f2f2; /* Добавляем разделительную черту снизу */
}
/* цвет ссылок */
#breadcrumbs a, #breadcrumbs a:visited {
color: #215B9B; /* Цвет ссылки */
text-decoration: none; /* Отменяем подчеркивание ссылок */
}
/* цвет ссылок при наведении курсора */
#breadcrumbs a:hover, #breadcrumbs a:active {
color: #C6C600; /* цвет ссылки при наведении курсора */
text-decoration: none; /* Отменяем подчеркивание ссылок при наведении курсора */
}Расширенные "Хлебные крошки"
В файл functions.php и в самый конец, перед знаком ?>, вставляем следующую функцию:
/*** Функция хлебных крошек ***/
function mayak_breadcrumbs_new() {
$mayak_home = 'Главная'; // текст ссылки "Главная"
$mayak_last_crumb = 1; // 1 - показывать название текущей статьи/страницы/рубрики, 0 - не показывать
$mayak_between = ' » ';
$mayak_from = '<span class="current-crumbs">';
$mayak_to = '</span>';
global $post;
$mayak_link_to_home = home_url('/');
$mayak_from_court = '<span typeof="v:Breadcrumb">';
$mayak_to_court = '</span>';
$mayak_link_rdf = ' rel="v:url" property="v:title"';
$mayak_path = $mayak_from_court . '<a' . $mayak_link_rdf . ' href="%1$s">%2$s</a>' . $mayak_to_court;
$mayak_superior = $descendant = $post->post_parent;
$mayak_initial_page = get_option('page_on_front');
if (is_home() || is_front_page()) {
echo '<div class="block-crumbs"><a href="'. $mayak_link_to_home.'">' . $mayak_home . '</a></div>';
} else {
echo '<div class="block-crumbs" xmlns:v="http://rdf.data-vocabulary.org/#">';
{
echo '<a href="'. $mayak_link_to_home.'" rel="v:url" property="v:title">' . $mayak_home . '</a>';
if ($mayak_initial_page == 0 || $mayak_superior != $mayak_initial_page) echo $mayak_between;
}
if ( is_category() ) {
$this_category = get_category(get_query_var('cat'), false);
if ($this_category->parent != 0) {
$category = get_category_parents($this_category->parent, TRUE, ' ' . $mayak_between. ' ');
if ($mayak_last_crumb == 1) $category = preg_replace("#^(.+)$mayak_between$#", "$1", $category);
$category = str_replace('<a', $mayak_from_court . '<a' . $mayak_link_rdf, $category);
$category = str_replace('</a>', '</a>' . $mayak_to_court, $category);
echo $category;
}
if ($mayak_last_crumb == 1) echo $mayak_from. sprintf(' Категория "' . single_cat_title('', false) . '"') .$mayak_to;
} elseif ( is_search() ) {
echo $mayak_from. sprintf('Результаты поиска для "' . get_search_query() . '"') .$mayak_to;
} elseif ( is_day() ) {
echo sprintf($mayak_path, get_year_link(get_the_time('Y')), get_the_time('Y')) .$mayak_between;
echo sprintf($mayak_path, get_month_link(get_the_time('Y'),get_the_time('m')), get_the_time('F')) .$mayak_between;
echo $mayak_from. get_the_time('d') .$mayak_to;
} elseif ( is_month() ) {
echo sprintf($mayak_path, get_year_link(get_the_time('Y')), get_the_time('Y')) .$mayak_between;
echo $mayak_from. get_the_time('F') .$mayak_to;
} elseif ( is_year() ) {
echo $mayak_from. get_the_time('Y') .$mayak_to;
} elseif ( is_single() && !is_attachment() ) {
if ( get_post_type() != 'post' ) {
$post_specimen = get_post_type_object(get_post_type());
$sleaze = $post_specimen->rewrite;
printf($mayak_path, $mayak_link_to_home . '/' . $sleaze['sleaze'] . '/', $post_specimen->labels->singular_name);
if ($mayak_last_crumb == 1) echo $mayak_between . mayak_from . get_the_title() . $mayak_to;
} else {
$cat = get_the_category(); $cat = $cat[0];
$category = get_category_parents($cat, TRUE, ' ' . $mayak_between . ' ');
if ($mayak_last_crumb == 0) $category = preg_replace("#^(.+)$mayak_between$#", "$1", $category);
$category = str_replace('<a', $mayak_from_court . '<a' . $mayak_link_rdf, $category);
$category = str_replace('</a>', '</a>' . $mayak_to_court, $category);
echo $category;
if ($mayak_last_crumb == 1) echo $mayak_from. get_the_title() . $mayak_to;
}
} elseif ( !is_single() && !is_page() && get_post_type() != 'post' && !is_404() ) {
$post_specimen = get_post_type_object(get_post_type());
echo $mayak_from. $post_specimen->labels->singular_name . $mayak_to;
} elseif ( is_attachment() ) {
$superior = get_post($mayak_superior);
$cat = get_the_category($superior->ID); $cat = $cat[0];
if ($cat) {
$category = get_category_parents($cat, TRUE, ' ' . $mayak_between . ' ');
$category = str_replace('<a', $mayak_from_court . '<a' . $mayak_link_rdf, $category);
$category = str_replace('</a>', '</a>' . $mayak_to_court, $category);
echo $category;
}
printf($mayak_path, get_permalink($superior), $superior->post_title);
if ($mayak_last_crumb == 1) echo $mayak_between . $mayak_from . get_the_title() . $mayak_to;
} elseif ( is_page() && !$mayak_superior ) {
if ($mayak_last_crumb == 1) echo $mayak_from . get_the_title() . $mayak_to;
} elseif ( is_page() && $mayak_superior ) {
if ($mayak_superior != $mayak_initial_page) {
$breadcrumbs = array();
while ($mayak_superior) {
$page = get_page($mayak_superior);
if ($mayak_superior != $mayak_initial_page) {
$breadcrumbs[] = sprintf($mayak_path, get_permalink($page->ID), get_the_title($page->ID));
}
$mayak_superior = $page->post_parent;
}
$breadcrumbs = array_reverse($breadcrumbs);
for ($i = 0; $i < count($breadcrumbs); $i++) {
echo $breadcrumbs[$i];
if ($i != count($breadcrumbs)-1) echo $mayak_between;
}
}
if ($mayak_last_crumb == 1) {
if ($descendant != 0 && $descendant != $mayak_initial_page) echo $mayak_between;
echo $mayak_from. get_the_title() .$mayak_to;
}
} elseif ( is_tag() ) {
echo $mayak_from. sprintf('Записи с меткой "%s"', single_tag_title('', false)) . $mayak_to;
} elseif ( is_author() ) {
global $author;
$userdata = get_userdata($author);
echo $mayak_from. sprintf('Записи автора за %s', $userdata->display_name) . $mayak_to;
} elseif ( is_404() ) {
echo $mayak_from. 'Ошибка 404' . $mayak_to;
} elseif ( has_post_format() && !is_singular() ) {
echo get_post_format_string(get_post_format() );
}
if ( get_query_var('paged') ) {
if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ' (';
echo 'Страница ' . get_query_var('paged');
if ( is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author() ) echo ')';
}
echo '</div>';
}
}
/*** Конец функции хлебных крошек ***/Вызов функции "Хлебных крошек"
Открываем сразу несколько файлов, которые отвечают за вывод:
- записей (single.php),
- страниц (page.php),
- архивов (archve.php),
- рубрик (category.php),
- меток (tag.php),
- страницы поиска (search.php),
- страницы автора (author.php),
- файл страницы ошибки 404 (404.php).
В открытых файлах ищем:
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
И перед ней вставляем код вызова функции:
<?php mayak_breadcrumbs_new(); ?>
CSS:
/*** Стили для хлебных крошек ***/
.block-crumbs{
margin: 5px 25px; /* Внешние отступы от блока */
padding-bottom:5px; /* Нижний внутренний отступ от блока */
border-bottom:2px solid #f2f2f2; /* Черта под блоком */
color:#215B9B; /* Цвет ссылок и текста в блоке */
}
.block-crumb a:hover,.block-crumb a:active {
color:#C6C600; /* Цвет ссылок при наведении и активном состоянии */
}
.current-crumbs{
color:#000; /* Цвет текста для последней крошки */
}Отключение редактирования файлов в панели администратора
wp-config.php
DEFINE ('DISALLOW_FILE_EDIT', TRUE); /*Запрет на изменение файлов в редакторе WP*/
DEFINE ('DISALLOW_FILE_MODS', TRUE); /*Запретить установку обновлений*/Счётчик просмотров
В funtions.php перед закрывающим тегом вставляем код функции:
/* Подсчет количества посещений страниц
---------------------------------------------------------- */
add_action('wp_head', 'kama_postviews');
function kama_postviews() {
/* ------------ Настройки -------------- */
$meta_key = 'views'; // Ключ мета поля, куда будет записываться количество просмотров.
$who_count = 1; // Чьи посещения считать? 0 - Всех. 1 - Только гостей. 2 - Только зарегистрированных пользователей.
$exclude_bots = 1; // Исключить ботов, роботов, пауков и прочую нечесть :)? 0 - нет, пусть тоже считаются. 1 - да, исключить из подсчета.
global $user_ID, $post;
if(is_singular()) {
$id = (int)$post->ID;
static $post_views = false;
if($post_views) return true; // чтобы 1 раз за поток
$post_views = (int)get_post_meta($id,$meta_key, true);
$should_count = false;
switch( (int)$who_count ) {
case 0: $should_count = true;
break;
case 1:
if( (int)$user_ID == 0 )
$should_count = true;
break;
case 2:
if( (int)$user_ID > 0 )
$should_count = true;
break;
}
if( (int)$exclude_bots==1 && $should_count ){
$useragent = $_SERVER['HTTP_USER_AGENT'];
$notbot = "Mozilla|Opera"; //Chrome|Safari|Firefox|Netscape - все равны Mozilla
$bot = "Bot/|robot|Slurp/|yahoo"; //Яндекс иногда как Mozilla представляется
if ( !preg_match("/$notbot/i", $useragent) || preg_match("!$bot!i", $useragent) )
$should_count = false;
}
if($should_count)
if( !update_post_meta($id, $meta_key, ($post_views+1)) ) add_post_meta($id, $meta_key, 1, true);
}
return true;
}Для просмотра на странице вставляем в single.php:
Просмотров: <?php echo get_post_meta ($post->ID,'views',true); ?>
Внутри функции есть её настройки: название ключа у произвольного поля, кого считать и исключить ботов или нет.
Название ключа нужно для того, чтобы можно было заменить, какой-нибудь другой плагин, который тоже использует произвольные поля для записи посещений. Например, если стоял плагин, который изменял произвольное поле с названием 'post_meta_name', то чтобы его заменить нужно изменить на 'post_meta_name' переменную $mata_key в функции и заменить 'views', при выводе числа посещений:
Просмотров: <?php echo get_post_meta ($post->ID,'post_meta_name',true); ?>
Убрать из блока "Мета" в сайдбаре ссылку на сайт WordPress
Открываем файл: wp-includes/default-widgets.php и с помощью поиска ищем и удаляем:
<?php /** * Filter the "Powered by WordPress" text in the Meta widget. * * @since 3.6.0 * * @param string $title_text Default title text for the WordPress.org link. */ echo apply_filters( 'widget_meta_poweredby', sprintf( '<li><a href="%s" title="%s">%s</a></li>', esc_url( __( 'https://wordpress.org/' ) ), esc_attr__( 'Powered by WordPress, state-of-the-art semantic personal publishing platform.' ), _x( 'WordPress.org', 'meta widget link text' ) ) ); wp_meta(); ?>
Также, в файле темы: wp-content/themes/название_темы/sidebar.php
Отключение ревизий
В wp-includes → default-constants.php найти код:
function wp_functionality_constants( ) {
. . .
if ( !defined('WP_POST_REVISIONS') )
define('WP_POST_REVISIONS', true);
. . .
}И заменить true на false:
if ( !defined('WP_POST_REVISIONS') )
define('WP_POST_REVISIONS', false);или в wp-config.php после:
define('DB_COLLATE', '');вставить:
define('WP_POST_REVISIONS', false);или:
define('WP_POST_REVISIONS', 0);можно указать количество ревизий:
define('WP_POST_REVISIONS', 2);Удаление старых ревизий и отключение
Сделать резервную копию БД. Выполнить SQL-запрос:
DELETE a,b,c FROM wp_posts a LEFT JOIN wp_term_relationships b ON (a.ID = b.object_id) LEFT JOIN wp_postmeta c ON (a.ID = c.post_id) WHERE a.post_type = 'revision';
Префикс wp_ должен быть такой, какой прописывался при установке.
Закрыть сайт на техническое обслуживание без плагина
В корне сайта создать файл с названием .maintenance с таким содержанием:
<?php
function is_user_logged_in() {
$loggedin = false;
foreach ( (array) $_COOKIE as $cookie => $value ) {
if ( stristr($cookie, 'wordpress_logged_in_') )
$loggedin = true;
}
return $loggedin;
}
if ( !stristr($_SERVER['REQUEST_URI'], '/wp-admin/') && !stristr($_SERVER['REQUEST_URI'], '/wp-login.php') && !is_user_logged_in() ) $upgrading = time();
?>Для того, чтобы вывести пользовательское сообщение, можно поместить в папку wp-content файл maintenance.php примерно такого содержания:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Блог закрыт</title>
<style>
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
::-moz-selection {
background: #b3d4fc;
text-shadow: none;
}
::selection {
background: #b3d4fc;
text-shadow: none;
}
.container {
position: absolute;
width: 400px;
height: 250px;
line-height: 250px;
text-align: center;
font-size: 18px;
left: 50%;
top: 50%;
margin-left: -200px;
margin-top: -125px;
box-shadow: 0 1px 10px #a7a7a7, inset 0 1px 0 #fff;
}
</style>
</head>
<body>
<div class="container">Блог закрыт на техническое обслуживание</div>
</body>
</html>Отключить замену кавычек в WordPress
В function.php после <?php
if ( function_exists('remove_filter') ) {
remove_filter('the_content', 'wptexturize');
remove_filter('the_title', 'wptexturize');
remove_filter('comment_text', 'wptexturize');
}Отключить уведомления об обновлении (от 3.0)
//отключение обновления WordPress
add_filter('pre_site_transient_update_core',create_function('$a', "return null;"));
wp_clear_scheduled_hook('wp_version_check');
//отключение обновлений плагинов
remove_action( 'load-update-core.php', 'wp_update_plugins' );
add_filter( 'pre_site_transient_update_plugins', create_function( '$a', "return null;" ) );
wp_clear_scheduled_hook( 'wp_update_plugins' );
//отключение обновлений тем
remove_action('load-update-core.php','wp_update_themes');
add_filter('pre_site_transient_update_themes',create_function('$a', "return null;"));
wp_clear_scheduled_hook('wp_update_themes');Можно в wp-config.php
define( 'AUTOMATIC_UPDATER_DISABLED', true );
Учтите, это отключит также автоматические обновления плагинов, шаблонов, языковых пакетов.
Или в functions.php
add_filter( 'auto_update_core', '__return_false' );
Скрыть значок об обновлениях - в functions.php
//удаление из панели элементов меню start
function wph_new_toolbar() {
global $wp_admin_bar;
$wp_admin_bar->remove_menu('updates'); //меню "обновления"
}
add_action('wp_before_admin_bar_render', 'wph_new_toolbar');
//удаление из панели элементов меню endКак удалить пункты из админ-меню WordPress
add_action('wp_before_admin_bar_render', 'udalit_punkti_menu_admina');
function udalit_punkti_menu_admina() {
global $wp_admin_bar;
$wp_admin_bar->remove_node('wp-logo'); // Логотип WordPress
$wp_admin_bar->remove_node('site-name'); // Название сайта
$wp_admin_bar->remove_node('my-account'); // "Привет, администратор", меню аккаунта
$wp_admin_bar->remove_node('about'); // "О WordPress"
$wp_admin_bar->remove_node('wporg'); // Ссылка на wordpress.org
$wp_admin_bar->remove_node('documentation'); // "Документация"
$wp_admin_bar->remove_node('support-forums'); // "форумы поддержки"
$wp_admin_bar->remove_node('feedback'); // "Обратная связь"
$wp_admin_bar->remove_node('view-site'); // "Перейти на сайт"
$wp_admin_bar->remove_node('comments'); // Комментарии, ожидающие проверки
$wp_admin_bar->remove_node('new-content'); // "Добавить"
$wp_admin_bar->remove_node('new-post'); // Добавить новую запись
$wp_admin_bar->remove_node('new-page'); // Добавить новую страницу
$wp_admin_bar->remove_node('new-media'); // Добавить новый медиафайл
$wp_admin_bar->remove_node('new-link'); // Добавить новую ссылку
$wp_admin_bar->remove_node('new-user'); // Добавить нового пользователя
}Скрыть меню из WordPress для всех, кто не является администратором:
add_action( 'admin_init', 'remove_menu_nonadmin' );
function remove_menu_nonadmin () {
global $user_ID;
if ( !current_user_can('administrator') ) {
remove_menu_page('index.php'); //страницы
remove_menu_page('tools.php'); //инструменты
remove_menu_page('edit.php?post_type=essential_grid'); // Essenzial Grid
remove_menu_page('wpcf7'); // Contact Form 7
remove_menu_page('vc-welcome'); // WPBakery Page Builder (Visual Composer)
}
}Добавить кнопки в редактор TinyMCE
В function.php:
//добавление новых кнопок в редактор start
function wph_new_buttons($buttons) {
$buttons[] = 'fontselect'; //семейство шрифтов
$buttons[] = 'fontsizeselect'; //размеры шрифтов
$buttons[] = 'styleselect'; //форматы
$buttons[] = 'cut'; //вырезать
$buttons[] = 'copy'; //копировать
$buttons[] = 'paste'; //вставить
$buttons[] = 'superscript'; //верхний индекс
$buttons[] = 'subscript'; //нижний индекс
$buttons[] = 'blockquote'; //цитата
return $buttons;
}
add_filter("mce_buttons_3", "wph_new_buttons");
//добавление новых кнопок в редактор endПереход на HTTPS
1) wp-config:
define('FORCE_SSL_ADMIN', true);2) Настройки → Общие → изменить ссылки на https
3) Установить плагин HTTP / HTTPS Remover Или запрос к базе. Если какие-то http ссылки остались, найти их в исходном коде страницы и устранить.
4) Сделать редирект с http на https
100% качество изображений
add_filter( 'jpg_quality', 'high_jpg_quality' );
function high_jpg_quality() {
return 100;
}Пользовательский CSS в админ-панели
add_action('admin_head', 'my_custom_fonts');
function my_custom_fonts() {
echo '<style>
body, td, textarea, input, select {
font-family: "Lucida Grande";
font-size: 12px;
}
</style>';
}Пример:
<?php
// Add inline CSS in the admin head with the style tag
function my_custom_admin_head() {
echo '<style>[for="wp_welcome_panel-hide"] {display: none !important;}</style>';
}
add_action( 'admin_head', 'my_custom_admin_head' );
// Add inline JS in the admin head with the <script> tag
function my_custom_admin_head() {
echo '<script type=""text/javascript">console.log('admin script')</script>';
}
add_action( 'admin_head', 'my_custom_admin_head' );
?>Или так:
add_action('admin_head', 'my_custom_fonts');
function my_custom_fonts() {
echo '<link rel="stylesheet" href="style.css" type="text/css" media="all" />';
}Или так:
function registerCustomAdminCss(){
$src = "URL/custom-admin-css.css";
$handle = "customAdminCss";
wp_register_script($handle, $src);
wp_enqueue_style($handle, $src, array(), false, false);
}
add_action('admin_head', 'registerCustomAdminCss');Или так:
function my_custom_fonts() {
wp_enqueue_style(‘admin_styles’ , get_template_directory_uri().’/css/admin_section.css’);
}
add_action(‘admin_head’, ‘my_custom_fonts’);Или так:
function my_admin_theme_style() {
wp_enqueue_style('my-admin-style', get_template_directory_uri() . '/path/to/admin/style.css');
}
add_action('admin_enqueue_scripts', 'my_admin_theme_style');Для плагина:
function my_admin_theme_style() {
wp_enqueue_style('my-admin-theme', plugins_url('wp-admin.css', __FILE__));
}
add_action('admin_enqueue_scripts', 'my_admin_theme_style');
add_action('login_enqueue_scripts', 'my_admin_theme_style');CSS и JS:
/**
* Define a version number
* This is optional but useful to circumvent caching issues
*
* There are more creative ways to get the version
* eg: if you get the version of the current theme and use that
* you'll never have to update the enque stuff manually
* so long as you update your theme version (but the version
* might be wrong if you're using a js or css library)
*
*/
$ver = '1.1.1';
/**
* Define the base url for the file
* In the 'active example below, it's assumed the files are in
* the child-theme folder
*
* Other examples:
*
* $base_url = get_template_directory_uri();
* If files are in the theme folder
*
* $base_url = plugin_dir_url( __FILE__ );
* If you're loading the files in a plguin
* I dont recommend you mess with plugin folders unless
* it's one you built yourself
*
*/
$base_url = get_stylesheet_directory_uri(); //
/**
* Enqueue and register Admin JavaScript files here.
* more at https://codex.wordpress.org/Function_Reference/wp_enqueue_script
*/
$js_dependancies = array( 'jquery' ); // OPTIONAL - jquery is just an example of an average js library you might need
function register_admin_scripts() {
wp_enqueue_script( 'solution-hotspots', $base_url . '/your-path/your-js-file.js', $js_dependancies, $ver );
}
/**
* Enqueue and register CSS files here.
* more at https://codex.wordpress.org/Function_Reference/wp_enqueue_style
*/
$css_dependancies = array();
function register_admin_styles() {
wp_enqueue_style( 'style-name', $base_url . '/your-path/your-css-file.css', $css_dependancies, $ver );
}
/**
* Make sure to spit it out!
*/
add_action( 'admin_enqueue_scripts', 'register_admin_scripts' );
add_action( 'admin_enqueue_scripts', 'register_admin_styleИ в админ-панели и в теме:
function change_adminbar_css() {
wp_register_style( 'add-admin-stylesheet', plugins_url( '/css/adminstyle.css', __FILE__ ) );
wp_enqueue_style( 'add-admin-stylesheet' );
}
add_action( 'admin_enqueue_scripts', 'change_adminbar_css' );
if (!is_admin) {
add_action( 'wp_enqueue_scripts', 'change_adminbar_css' );
}С указанием роли пользователя:
add_action('admin_head', 'my_custom_fonts');
function my_custom_fonts() {
global $user_level;
if ($user_level != '10' ) {
echo '
/* Styles here! */
';
}}Для разных ролей:
function my_custom_css( ){
global $user;
if (isset($user->roles) && is_array( $user->roles ) ) {
if( $user->roles[0] == 'administrator' ) {
//Do something
} elseif ( $user->roles[0] == 'shop-manager' ) {
//Do something
} elseif ( $user->roles[0] == 'editor' ) {
//Do something
} elseif ( $user->roles[0] == 'author' ) {
//Do something
} elseif ( $user->roles[0] == 'customer' || $user->roles[0] == 'subscriber' ) {
//Do something
} elseif ( $user->roles[0] == 'contributor') {
//Do something
} else {
//Do something
}
}
}В примере выше лучше использовать:
add_action( 'admin_enqueue_scripts', 'my_custom_fonts' );
вместо:
add_action('admin_head', 'my_custom_fonts');Или так:
add_action('admin_head', 'my_custom_fonts');
function my_custom_fonts() {
wp_enqueue_style('style-admin' ,plugin_dir_url(FILE) .'css/style-admin.css');
}Разные CSS для админ-панели и темы:
if (is_admin()) add_action('admin_head', 'load_backend_css');
if (!is_admin()) add_action('wp_head', 'load_frontend_css');
function load_backend_css() {
echo '<style>YOUR CSS GOES HERE</style>';
}
function load_frontend_css() {
echo '<style>YOUR CSS GOES HERE</style>';
}Только для темы, если пользователь залогинился:
if (is_admin()) add_action('admin_head', 'load_backend_css');
if (!is_admin() && is_user_logged_in()) add_action('wp_head', 'load_frontend_css');
function load_backend_css() {
echo '<style>Your CSS goes here</style>';
}
function load_frontend_css() {
echo '<style>Your CSS goes here</style>';
}Изменить цвет верхней панели управления
add_action( 'admin_head', 'true_colored_admin_bar_0073aa' );
function true_colored_admin_bar_0073aa(){
echo '<style>#wpadminbar{background-color: #0073aa;}</style>'; // выводим стили
}Перевод ссылок в комментариях в текст
// запрет ссылок в комментах
function remove_link_comment($link_text) {
return strip_tags($link_text);
}
add_filter('pre_comment_content','remove_link_comment');
add_filter('comment_text','remove_link_comment');или:
remove_filter('comment_text', 'make_clickable', 9);Запретить редактирование файлов в админке
wp-config.php:
define('DISALLOW_FILE_EDIT', true);Переход на главную после нажатия ссылки "Выйти" в консоли
add_action('wp_logout','my_wp_logout');
function my_wp_logout() {
wp_safe_redirect('/');
exit;
};Отключить админ панель для всех, кроме администраторов
/* Отключаем админ панель для всех, кроме администраторов. */
if (!current_user_can('administrator')):
show_admin_bar(false);
endif;или:
add_action('after_setup_theme', 'remove_admin_bar');
function remove_admin_bar() {
if (!current_user_can('administrator') && !is_admin()) {
show_admin_bar(false);
}
}или:
function my_function_admin_bar($content) {
return ( current_user_can("administrator") ) ? $content : false;
}
add_filter( 'show_admin_bar' , 'my_function_admin_bar');Если вы хотите удалить верхнюю панель, то для этого необходимо запретить инициализировать скрипты, отображающие ее, и убрать все настройки верхней панели из вашего профиля. Для того, чтобы удалить панель для всех, но оставить видимой для администратора, используйте в файле functions.php код:
function hide_admin_bar_settings() {
?>
<style type="text/css">
.show-admin-bar {
display: none;
}
</style>
<?php
}
function disable_admin_bar() {
if ( !current_user_can("administrator") ) {
add_filter( 'show_admin_bar', '__return_false' );
add_action( 'admin_print_scripts-profile.php',
'hide_admin_bar_settings' );
}
}
add_action( 'init', 'disable_admin_bar' , 9 );Если же вы хотите полностью избавить от верхней панели всех пользователей, в том числе и администраторов, то используйте этот код:
add_filter( 'show_admin_bar', '__return_false' ); ?>
<?php function hide_admin_bar_settings() {
?>
<style type="text/css">
.show-admin-bar {
display: none;
}
</style>
<?php
}
function disable_admin_bar() {
add_filter( 'show_admin_bar', '__return_false' );
add_action( 'admin_print_scripts-profile.php',
'hide_admin_bar_settings' );
}
add_action( 'init', 'disable_admin_bar' , 9 );Отключить админ панель для всех пользователей
add_filter('show_admin_bar', '__return_false');или:
/* Отключаем админ панель для всех пользователей. */ show_admin_bar(false);
Для новых пользователей по умолчанию убрать галочку "
Показывать верхнюю панель при просмотре сайта " в профиле:
function set_user_admin_bar_false_by_default($user_id) {
update_user_meta( $user_id, 'show_admin_bar_front', 'false' );
}
add_action('user_register', 'set_user_admin_bar_false_by_default', 10, 1);Отключить настройки экрана для всех пользователей, кроме администратора
function wpb_remove_screen_options() {
if(!current_user_can('manage_options')) {
return false;
}
return true;
}
add_filter('screen_options_show_screen', 'wpb_remove_screen_options');Вставить Slider Revolution
<?php
echo do_shortcode( '[rev_slider alias="test"][/rev_slider]' );
?>CSS для главной
<?php if( is_home() || is_front_page() ) : ?>
<style id="my-internal-css">
#main_content .container {
position: relative;
padding: 120px 0;
}
</style>
<?php endif; ?>Подобно is_single(), is_page(), is_category(), is_archive(), is_day() и т.п.
<head>
<?php if(is_home()){ ?>
<style>
.container{width:100%!important;}
</style>
<?php } ?>
</head>С условием else:
<?php if(is_home()){ ?>
<div class="container" style="width:100%!important;">
<?php } else { ?>
<div class="container">
<?php } ?>
//content....
</div>Или внешнее подключение:
<?php
if(is_home()){
// we are on the home page
echo '<link rel="stylesheet" src="your_stylesheet" />';
}
?><?php
if(is_home()){
// we are on the home page
echo '<link rel="stylesheet" src="your_home_stylesheet" />';
}else {
echo '<link rel="stylesheet" src="your_default_stylesheet" />';
}
?>Отключить автоматические параграфы
remove_filter('the_content', 'wpautop');Ссылка в ToolBar (AdminBar)
// добавляем ссылку на панель WordPress
function custom_toolbar_link($wp_admin_bar) {
$args = array(
'id' => 'wpincode',
'title' => 'Поиск по WPBegginer',
'href' => 'https://www.google.com:443/cse/publicurl?cx=014650714884974928014:oga60h37xim',
'meta' => array(
'class' => 'wpincode',
'title' => 'Поиск по WPBegginer'
)
);
$wp_admin_bar->add_node($args);
}
add_action('admin_bar_menu', 'custom_toolbar_link', 999);или:
function wp_admin_bar_new_link() {
global $wp_admin_bar;
$wp_admin_bar->add_menu(array(
'id' => 'wp-admin-bar-new-link',
'title' => __('Помощь по WP'),
'href' => 'https://translate.google.com/'
));
}
add_action('wp_before_admin_bar_render', 'wp_admin_bar_new_link');несколько:
function wp_admin_bar_new_link() {
global $wp_admin_bar;
$wp_admin_bar->add_menu(
array(
'id' => 'wp-admin-bar-new-link',
'title' => __('Помощь по WP'),
'href' => 'https://translate.google.com/'
));
$wp_admin_bar->add_menu(
array(
'id' => 'wp-admin-bar-new-link2',
'title' => __('Цены на услуги'),
'href' => 'https://support.google.com/translate/#topic=7011755'
));
}
add_action('wp_before_admin_bar_render', 'wp_admin_bar_new_link');группа произвольных ссылок:
/*
* добавляем группу ссылок под одну родительскую ссылку
*/
// Добавляем родительскую ссылку
function custom_toolbar_link($wp_admin_bar) {
$args = array(
'id' => 'wpincode',
'title' => 'WPinCode',
'href' => 'https://www.wpincode.com',
'meta' => array(
'class' => 'wpincode',
'title' => 'Посетить WPinCode'
)
);
$wp_admin_bar->add_node($args);
// Добавляем первую дочернюю ссылку
$args = array(
'id' => 'wpincode-guides',
'title' => 'WPinCode Guides',
'href' => 'http://www.wpincode.com/category/beginners-guide/',
'parent' => 'wpincode',
'meta' => array(
'class' => 'wpincode-guides',
'title' => 'Посетить WordPress WPinCode Guides'
)
);
$wp_admin_bar->add_node($args);
// Добавляем еще одну дочернюю ссылку
$args = array(
'id' => 'wpincode-tutorials',
'title' => 'WPinCode Tutorials',
'href' => 'http://www.wpincode.com/category/wp-tutorials/',
'parent' => 'wpincode',
'meta' => array(
'class' => 'wpincode-tutorials',
'title' => 'Посетить WPinCode Tutorials'
)
);
$wp_admin_bar->add_node($args);
// Добавляем дочерную ссылку под дочернюю ссылку
$args = array(
'id' => 'wpincode-themes',
'title' => 'WPinCode Themes',
'href' => 'http://www.wpincode.com/category/wp-themes/',
'parent' => 'wpincode-tutorials',
'meta' => array(
'class' => 'wpincode-themes',
'title' => 'Посетить WPinCode Themes Tutorials на WPinCode'
)
);
$wp_admin_bar->add_node($args);
}
add_action('admin_bar_menu', 'custom_toolbar_link', 999);Запретить любое обновление и редактирование в WordPress
wp-config.php:
define('DISALLOW_FILE_MODS', true);- Установка новых тем;
- Изменение существующих тем;
- обновление тем;
- Установка новых плагинов;
- Изменение существующих плагинов;
- обновление плагинов;
- обновление версии CMS WordPress.
Ограничение количества символов в описании
// Ограничение количества символов в описании
function new_excerpt_length($length) {
return 50;
}
add_filter('excerpt_length', 'new_excerpt_length');Установка максимальной длинны заголовка записи
function maxWord($title){
global $post;
$title = $post->post_title;
if (str_word_count($title) >= 10 ) //set this to the maximum number of words
wp_die( __('Error: your post title is over the maximum word count.') );
}
add_action('publish_post', 'maxWord');Режим восстановления
https://site/wp-login.php?action=entered_recovery_mode
wp_is_mobile ()
<?php if( wp_is_mobile() ) : ?>
Visit our website on your desktop for a richer user experience
<?php endif ?>