queries)) { usort($wpdb->queries, function($a, $b) { return $b[1] - $a[1]; }); $slow_queries = array_slice($wpdb->queries, 0, 5); foreach ($slow_queries as $i => $query) { $logs[] = "Медленный запрос #" . ($i+1) . ": " . round($query[1], 4) . " сек | " . substr(str_replace(["\n", "\r"], ' ', $query[0]), 0, 200) . "..."; } } $message = implode(" | ", $logs); file_put_contents($log_file, $message."\n\n", FILE_APPEND | LOCK_EX); }); */ add_action('before_rocket_clean_files', function ($urls) { foreach ($urls as $url) { if (str_contains($url, 'g.profile.ru') !== false) { return; } } $urls_for_clean = array_map(function ($url) { return str_replace('profile.ru', 'g.profile.ru', $url); }, $urls); \rocket_clean_files($urls_for_clean); return $urls; }, 1, 999); add_filter('rocket_clean_domain_urls', function ($urls, $lang) { $urls = [ "https://profile.ru", "https://g.profile.ru" ]; return $urls; }, 2, 999); add_action('before_rocket_clean_domain', function ($root, $lang, $url) { if (mb_stripos($url, 'g.profile.ru') !== false) { return; } rocket_clean_files(['https://g.profile.ru/']); return; }, 3, 999); add_filter('rocket_post_purge_urls', function ($purge_urls, $post) { $newurls = []; foreach ($purge_urls as $purge_url) { $newurls[] = str_replace('admin.profile.ru', 'profile.ru', $purge_url); $newurls[] = str_replace('admin.profile.ru', 'g.profile.ru', $purge_url); } //$newurls[] = 'https://g.profile.ru/'; return $newurls; }, 2, 999); add_action('before_rocket_clean_home', function($root, $lang){ $root = str_replace('/profile.ru*', '/g.profile.ru', $root); $files = glob( $root . '/*', GLOB_NOSORT ); if ( $files ) { foreach ( $files as $file ) { if ( preg_match( '#/index(?:-.+\.|\.)html(?:_gzip)?$#', $file ) ) { \rocket_direct_filesystem()->delete( $file ); } } } },2,999); /**********************************************************************************************************************/ $ver = '2.6.12'; $test_page_id = 216301; $colors = array ( "blue" => "Голубой", "indigo" => "Индиго", "purple" => "Пурпурный", "pink" => "Розовый", "red" => "Красный", "orange" => "Оранжевый", "yellow" => "Желтый", "green" => "Зеленый", "teal" => "Биюзовый", "cyan" => "Циан", "white" => "Белый", "gray" => "Серый", "gray-dark" => "Темно-серый", "light" => "Магнолия", "dark" => "Космос" ); $termTaxTypes = array ( "category" => "Рубрика", "story" => "Сюжет", "branding" => "Спецпроект" ); //проверка на рсску для Я.Н. function is_yn(){ if(mb_strripos(filter_input(INPUT_SERVER,'REQUEST_URI'),get_option('layf_custom_url')) !== false){ return true; } return false; } //проверка на рсску для Я.Д. function is_zen(){ if(mb_strripos(filter_input(INPUT_SERVER,'REQUEST_URI') ,get_option('yzrssname')) !== false && get_option('yzrssname') !== false){ return true; } return false; } /** * Это говно убрать в следующих итерациях */ /** add_filter('posts_orderby', function($order){ if((is_post_type_archive() || is_front_page()) && !is_admin() && !is_events()){ $order = " CASE WHEN ( pm123.meta_value = 1 ) THEN 1 ELSE 0 END DESC, wp_posts.post_date DESC "; } return $order; }); add_filter('posts_join', function($order){ if((is_post_type_archive() || is_front_page()) && !is_admin() && !is_events()){ $order .= " left join wp_postmeta pm123 on pm123.post_id = wp_posts.ID and pm123.meta_key = '_breaking' "; } return $order; }); */ //добавляем нестандартные типы материалов (новости, статьи) function add_article_in_main_query( $query ) { global $wp; if(is_yn()){ $query->set('tag__not_in', array(7840)); } $query->set('ep_integrate', false);//включили ep //var_dump( get_option('layf_custom_url')); if (is_admin()){ if (get_query_var('author_name')){ $query->set('post_type', array('profile_article','anew','yellow')); //echo ''; }else if (filter_input(INPUT_GET,'page') == 'wps_authors_page'){ $query->set('post_type', array('profile_article','anew','yellow')); $query->set('posts_per_page', -1); }else if (filter_input(INPUT_GET, 'id') == 'tag_request' && filter_input(INPUT_GET, 'post_id') == 103454){ $query->set('post_type', array('profile_article','anew', 'yellow')); } if(user_has_role(get_current_user_id(), 'intern')){ //$query->set('author__in', array(get_current_user_id())); } return $query; } else if ($query->is_post_type_archive() && !is_admin()){ $queried_object = get_queried_object(); if ($queried_object->name == 'archive'){ wp_redirect("/?s="); } $queried_object = ($queried_object->name == 'yellow') ? array($queried_object->name, "anew") : $queried_object->name; $query->set('post_type', $queried_object); } else { if ($query->is_feed()){ //фиды $query->set('post_type', array('profile_article','anew','yellow')); }else if( ($query->is_main_query() && is_tag() && get_queried_object()->term_id == 103454) || (filter_input(INPUT_GET, 'id') == 'tag_request' && filter_input(INPUT_GET, 'post_id') == 103454) ){ $query->set('post_type', array('profile_article', 'anew', 'yellow')); }else if ($query->is_main_query() && !is_admin() && is_author()){ //страница автора //$query->set('post_type', array('profile_article')); global $coauthors_plus; $guest_author_id = $coauthors_plus->get_coauthor_by('user_login', get_query_var( 'author_name' ))->ID; $only_articles = get_post_meta($guest_author_id, 'show_only_articles', true); if($only_articles){ $query->set('post_type', array('profile_article')); }else{ $query->set('post_type', array('profile_article','anew','yellow')); } }else if ($query->is_main_query() && !is_admin() && (is_category() || is_search() || is_archive())){ //страницы рубрик, поиска, архива if(is_search() && strlen(filter_input(INPUT_GET, 's', FILTER_SANITIZE_STRING)) < 5 && strlen(filter_input(INPUT_GET, 's', FILTER_SANITIZE_STRING)) != 0){ wp_redirect('/?s='); }else if (is_search() && strlen(filter_input(INPUT_GET, 's', FILTER_SANITIZE_STRING)) == 0){ //return false;die; } $query->set('post_type', array('profile_article','anew','yellow')); if(get_queried_object_id() == 104418){ $query->set('posts_per_page', 100); } }else if ($query->is_main_query() && !is_admin() && is_single()){ //страница материала $query->set('post_type', array('profile_article','anew','archive','yellow')); }else if ($query->is_main_query() && is_post_type_archive()){ //страница архива типа материала $query->set('post_type', get_query_var('post_type')); }else if ($query->is_main_query() && !is_home() && !is_single() && !is_page() && strripos(home_url( $wp->request ).'/', get_option('layf_custom_url')) !== false){ //фид я.новости $query->set('post_type', array('profile_article','anew','archive','yellow')); }else if ($query->is_main_query() && !is_home() && !is_single() && !is_page()) { //админка $query->set('post_type', array('profile_article', 'anew')); }else if ($query->is_main_query() && !is_admin()){ //все остальное $query->set('post_type', array('profile_article','page','anew')); } } if(is_tag() && !is_admin()){ $query->set('posts_per_page', 20); } return $query; } add_action( 'pre_get_posts', 'add_article_in_main_query' ); //обрабатываем вставку картинок в тело статьи add_filter( 'image_send_to_editor', 'custom_image_send_to_editor', 10, 8 ); function custom_image_send_to_editor( $html, $id, $caption, $title, $align, $url, $size, $alt ){ $auth = htmlspecialchars($caption); $html = str_replace(''; $return .= ''; $return .= ''; } return $return; }else{ return $output; } } add_filter( 'post_gallery', 'profile_gallery_shortcode', 10, 3 ); //собираем все свойства файла function wp_get_attachment( $attachment_id ) { $attachment = get_post( $attachment_id ); return array( 'alt' => htmlspecialchars(get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true )), 'caption' => htmlspecialchars($attachment->post_excerpt), 'description' => htmlspecialchars($attachment->post_content), 'href' => get_permalink( $attachment->ID ), 'src' => $attachment->guid, 'title' => htmlspecialchars($attachment->post_title) ); } //добавление копирайта к свойствам объекта изображения add_filter( 'wp_get_attachment_image_attributes', 'profile_get_attachment_image_attributes', 10, 3 ); function profile_get_attachment_image_attributes( $attr, $attachment, $size ) { if (!is_object($attr)) return $attr; $attr->copyright = wp_get_attachment_caption($attachment->ID); return $attr; } //копирайт для галереи function get_post_gallery_copyright($postID) { $gallery = get_post_gallery(get_post($postID), false); $attachment = wp_get_attachment(array_shift(explode(',',$gallery['ids']))); if (strlen($attachment['caption']) == 0){return;} return 'Фото: '.str_replace('Фото:','',$attachment['caption']); } //вывод описания для первого снимка галереи function get_post_gallery_description($postID) { $gallery = get_post_gallery(get_post($postID), false); $attachment = wp_get_attachment(array_shift(explode(',',$gallery['ids']))); return $attachment['description']; } //основная категория поста function get_post_primary_category($post_id, $term='category', $return_all_categories=false){ $return = array(); if (class_exists('WPSEO_Primary_Term')){ $wpseo_primary_term = new WPSEO_Primary_Term( $term, $post_id ); $primary_term = get_term($wpseo_primary_term->get_primary_term()); if (!is_wp_error($primary_term)){ $return['primary_category'] = $primary_term; } } if (empty($return['primary_category']) || $return_all_categories){ $categories_list = get_the_terms($post_id, $term); if (empty($return['primary_category']) && !empty($categories_list)){ $return['primary_category'] = $categories_list[0]; //get the first category } if ($return_all_categories){ $return['all_categories'] = array(); if (!empty($categories_list)){ foreach($categories_list as &$category){ $return['all_categories'][] = $category->term_id; } } } } return $return; } function get_post_primary_category_id($post_id){ $term = get_post_primary_category($post_id); $term = $term['primary_category']; return $term->term_id; } function is_branding_page(){ if (!is_object(get_queried_object())){ return false; } $out = get_term_meta(get_queried_object()->term_id,'type',1); return $out; } //парсинг класса тела сайта //правильные урлы function remove_cpt_slug( $post_link, $post, $leavename ) { if ( 'profile_article' != $post->post_type || 'publish' != $post->post_status ) { return $post_link; } $post_link = str_replace( '/' . $post->post_type . '/', '/', $post_link ); $post_link = str_replace( '/articles/', '/', $post_link ); return $post_link; } add_filter( 'post_type_link', 'remove_cpt_slug', 10, 3 ); function change_slug_struct( $query ) { if ( ! $query->is_main_query() || 2 != count( $query->query ) || ! isset( $query->query['page'] ) ) { return; } if ( ! empty( $query->query['name'] ) ) { $query->set( 'post_type', array( 'post', 'profile_article', 'page' ) ); } elseif ( ! empty( $query->query['category_name'] ) && false === strpos( $query->query['category_name'], '/' ) ) { $query->set( 'post_type', array( 'post', 'profile_article', 'page' ) ); $query->set( 'name', $query->query['category_name'] ); } } add_action( 'pre_get_posts', 'change_slug_struct' ); //проверка наличия тега more function maybe_has_more_link( $post_id ) { $post = get_post( $post_id ); $content = $post->post_content; $data_array = get_extended( $content ); return '' !== $data_array['extended']; } //получаем первый абзац function get_first_paragraph(){ global $post; $str = ''; $i = 0; $content = wpautop( get_the_content() ); //debug('-'.$content); if(mb_strpos( $content, '

') === false){ return $content; } while($str == ''){ $i++; $str = mb_substr( $content, 0, mb_strpos( $content, '

', $i*7 ) + 4 ); $str = strip_shortcodes(strip_tags($str)); } return $str; } //не пробелом единым function strposa($haystack, $needles=array(), $offset=0) { $chr = array(); foreach($needles as $needle) { $res = mb_stripos($haystack, $needle, $offset); if ($res !== false) $chr[$needle] = $res; } if(empty($chr)) return false; return min($chr); } //генерим анонс со всеми условиями function the_announce(){ global $post; global $more; $more = 1; $len = 200;//количество символов $end = '...'; $more = maybe_has_more_link($post->ID); $content = get_post_field( 'post_content', $post->ID); $content_parts = get_extended( $content ); if ($more && mb_strlen(strip_tags($content_parts['main'])) < $len){ if (mb_strlen(strip_tags($content_parts['main'])) > 50){ echo strip_tags($content_parts['main']).$end; }else{ $p = get_first_paragraph(); if (mb_strlen($p) < $len){ echo $p.$end; }else{ $length = strposa($p, array(" ",".",",",";","'","\""),$len); echo mb_substr($p, 0, ((int)$length+(int)$len)).$end; } } }else{ $p = get_first_paragraph(); if (mb_strlen($p) < $len){ echo $p.$end; }else{ $length = strposa($p, array(" ",".",",",";","'","\""),$len); echo mb_substr($p, 0, ((int)$length+(int)$len)).$end; } } } //убираем лишнее из РСС function full_text_formatting_rss($content){ $content = htmlspecialchars(html_entity_decode($content)); return $content; } function test_full_text_formatting_rss($content){ $content = htmlspecialchars_decode(html_entity_decode($content)); return $content; } add_filter('layf_content_feed', 'full_text_formatting_rss', 20); add_filter( 'layf_turbo_content_feed', 'full_text_formatting_rss', 20); apply_filters( 'bloginfo_rss', 'full_text_formatting_rss', 20 ); add_filter('get_the_excerpt', 'full_text_formatting_rss', 20); add_filter('the_excerpt_rss', 'full_text_formatting_rss', 20); add_filter( 'layf_turbo_content_feed', 'test_full_text_formatting_rss', 30 ); add_filter("the_content", function($content){ return str_replace( [ "123.profile.ru", "profile.ru:1234", "profile.ru:5678" ], "profile.ru", $content ); }, 999); // гутенберг бодрым шагом идет нахер add_filter('use_block_editor_for_post', '__return_false', 10); function debug($content){ if(!is_string($content)){ ob_start(); var_dump($content); $content = ob_get_clean(); } $request = "https://api.telegram.org/bot1184440628:AAE5N10dnzClx3Qce4v1mBD9ax1BsHo98Rs/sendMessage?chat_id=202319661&parse_mode=HTML&text=".urlencode($content); $ch = curl_init(); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_VERBOSE, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)'); curl_setopt($ch, CURLOPT_URL, $request); $return = curl_exec($ch); return true; } add_filter('the_content', function ($content) { $allow = [ "ТАСС", "TASS", "Профиль", "Shutterstock" ]; $preview = wp_is_mobile() ? get_template_directory_uri() . '/assets/img/Profile_lazyload_m.webp' : get_template_directory_uri() . '/assets/img/Profile_lazyload.jpg'; libxml_use_internal_errors(true); $dom = new DOMDocument(); $dom->loadHTML('' . $content); $images = $dom->getElementsByTagName('img'); foreach ($images as $image) { $capt = ""; $child = $image; $wrapper = $image->parentNode; if ($wrapper->tagName == 'p') { $id = (int)preg_replace('~\D+~','', $image->getAttribute('class')); $attachment = get_post($id); $figure = $dom->createElement('figure'); $figure->setAttribute('class', $image->getAttribute('class')); if(file_exists($image->getAttribute('src'))){ $mw = ((int)$image->getAttribute('width')) ? ((int)$image->getAttribute('width')) : (getimagesize($image->getAttribute('src')))[0]; $figure->setAttribute('style','max-width:'.$mw."px"); } if (!is_feed() && !is_amp_endpoint()) { $image->setAttribute('class', 'lazyload'); $image->removeAttribute('sizes'); $image->removeAttribute('srcset'); } if(get_queried_object_id() == 1089324 && wp_is_mobile()){ $image->setAttribute('data-src', $image->getAttribute('src')); $image->setAttribute('src', get_template_directory_uri() . '/assets/img/Profile_lazyload_m.webp'); $image->setAttribute('width', (int)$image->getAttribute('width') . 'px'); $image->setAttribute('height', (int)$image->getAttribute('height') . 'px'); } $figcaption = $dom->createElement('figcaption'); $auth = $dom->createElement('span'); if (strlen($image->getAttribute('data-auth')) !== 0 ) { $capt = $image->getAttribute('data-auth'); }else if(strlen($attachment->post_excerpt) !== 0 && $attachment->post_type == 'attachment' && !strposa($attachment->post_excerpt, ['instag', 'faceb', 'инстаг'])){ $capt = $attachment->post_excerpt; } if (mb_strlen($capt) === 0 && mb_strlen($image->getAttribute('alt')) !== 0 ){ $capt = $image->getAttribute('alt'); } $flag = true; if ( in_array( get_post_type(), ['anew', 'yellow'] ) && get_the_date("U") < 1719187200 ) { $flag = false; foreach ($allow as $c) { if(str_contains($capt, $c)) { $flag = true; } } } if ($flag === false) { $figure = $dom->createElement('div'); } $image->parentNode->replaceChild($figure, $image); if ($flag === false) { continue; } $figure->appendChild($child); $auth->nodeValue = "©".$capt; $figcaption->appendChild($auth); if(strlen($attachment->post_content) !== 0 && $attachment->post_type == 'attachment'){ $desc = $dom->createElement('p'); $desc->nodeValue = $attachment->post_content; $figcaption->appendChild($desc); } $figure->appendChild($figcaption); } } $html = str_replace(['', ''], '', $dom->saveHTML($dom->getElementsByTagName('body')->item(0))); $html = preg_replace_callback( '|
(.*)
|Uis', function($matches){ return str_ireplace('depositphotos.com', 'depositphotos.com', $matches[0]); }, $html ); libxml_use_internal_errors(false); //$html .= ''; return $html; }, 999, 1); //выебоны с галереей! function real_img_caption_shortcode( $attr, $content = null ) {//автор и название картинки if ( ! isset( $attr['caption'] ) ) { if ( preg_match( '#((?:]+>\s*)?]+>(?:\s*)?)(.*)#is', $content, $matches ) ) { $content = $matches[1]; $attr['caption'] = trim( $matches[2] ); } } elseif ( strpos( $attr['caption'], '<' ) !== false ) { $attr['caption'] = wp_kses( $attr['caption'], 'post' ); } $atts = shortcode_atts( array( 'id' => '', 'align' => 'alignnone', 'width' => '', 'caption' => '', 'class' => '', ), $attr, 'caption' ); $auth = preg_replace("/\".*/","",preg_replace("/.*data-auth=\"/","",$content)); if(strposa($auth, ['instag', 'faceb', 'инстаг']) > 0) { $auth = ''; } $html = '
' . do_shortcode( $content ) . '

' . $atts['caption'] . '

' . '' . $auth . '
'; return $html; } add_shortcode('wp_caption', 'real_img_caption_shortcode'); add_shortcode('caption', 'real_img_caption_shortcode'); //загрузка кастомных стилей function customStyles(){ if (is_branding()){ $file = 'branding-styles'; if (file_exists(__DIR__.'/'.$file.'.php')){ get_template_part( $file ); } } return true; } //это чтобы достать аватарку автора function coauthors_get_avatar_url( $coauthor, $size = 32, $default = '', $alt = false ) { global $coauthors_plus; if ( ! is_object( $coauthor ) ) { return ''; } if ( isset( $coauthor->type ) && 'guest-author' == $coauthor->type ) { $guest_author_thumbnail = $coauthors_plus->guest_authors->get_guest_author_thumbnail( $coauthor, $size ); if ( $guest_author_thumbnail ) { preg_match( '@src="([^"]+)"@' , $guest_author_thumbnail, $match ); $src = array_pop($match); return $src; } } if ( isset( $coauthor->user_email ) ) { preg_match( '@src="([^"]+)"@' , get_avatar( $coauthor->user_email, $size, $default, $alt ), $match ); $src = array_pop($match); return $src; } return ''; } //Убираем тирешечки add_action('wp_insert_post_data', 'dashes_replace', 10, 2); function dashes_replace($data, $postarr){ $data['post_content'] = str_replace(array(' - ', ' — '), ' – ', $data['post_content'] ); $data['post_content'] = str_replace(array('—'), '–', $data['post_content'] ); return $data; } //убрал эти стремные яблочные дефисы add_filter( 'wp_insert_post_data' , 'replace_MACOS_symbols' , 10, 1 ); function replace_MACOS_symbols( $data ) { $symbols = array( "\u001e" => "" ); $data['post_content'] = json_decode(strtr(json_encode($data['post_content']),$symbols)); return $data; } // хук для регистрации add_action( 'init', 'create_taxonomy' ); function create_taxonomy(){ register_taxonomy('archive_category', array('archive'), array( 'label' => '', // определяется параметром $labels->name 'labels' => array( 'name' => 'Рубрики архива архива', 'singular_name' => 'Рубрика архива', 'search_items' => 'Поиск по рубрикам архива', 'all_items' => 'Все рубрики архива', 'view_item ' => 'Посмотреть рубрику архива', 'parent_item' => 'родительская рубрика архива', 'parent_item_colon' => 'родительская рубрика архива:', 'edit_item' => 'Редактировать рубрику архива', 'update_item' => 'Обновить рубрику архива', 'add_new_item' => 'Добавить рубрику архива', 'new_item_name' => 'Имя новой рубрики архива', 'menu_name' => 'Рубрики архива', ), 'description' => '', // описание таксономии 'public' => true, 'publicly_queryable' => null, // равен аргументу public 'show_in_nav_menus' => true, // равен аргументу public 'show_ui' => true, // равен аргументу public 'show_in_menu' => true, // равен аргументу show_ui 'show_tagcloud' => true, // равен аргументу show_ui 'show_in_rest' => null, // добавить в REST API 'rest_base' => null, // $taxonomy 'hierarchical' => false, //'update_count_callback' => '_update_post_term_count', 'rewrite' => true, //'query_var' => $taxonomy, // название параметра запроса 'capabilities' => array(), 'meta_box_cb' => null, // callback функция. Отвечает за html код метабокса (с версии 3.8): post_categories_meta_box или post_tags_meta_box. Если указать false, то метабокс будет отключен вообще 'show_admin_column' => false, // Позволить или нет авто-создание колонки таксономии в таблице ассоциированного типа записи. (с версии 3.5) '_builtin' => false, 'show_in_quick_edit' => null, // по умолчанию значение show_ui ) ); } add_action( 'init', 'archive_register_post_type_init' ); function archive_register_post_type_init() { $labels = array( 'name' => 'Архив', 'singular_name' => 'Архивная запись', 'add_new' => 'Добавить в архив', 'add_new_item' => 'Добавить в архив', 'edit_item' => 'Редактировать запись', 'new_item' => 'Архивная запись', 'all_items' => 'Все записи архива', 'view_item' => 'Просмотр архива на сайте', 'search_items' => 'Искать в архиве', 'not_found' => 'В архиве не найдено.', 'not_found_in_trash' => 'В корзине нет архивных записей.', 'menu_name' => 'Архив' ); $args = array( 'labels' => $labels, 'public' => true, 'show_ui' => true, 'has_archive' => true, 'supports' => array( 'title', 'subtitle', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ), 'taxonomies' => array('post_tag','category'), 'rewrite' => array('slug' => 'archive','with_front' => true), 'can_export' => true, 'show_in_menu' => false, 'menu_position' => 5, 'show_in_nav_menus' => false, 'publicly_queryable' => true, 'exclude_from_search' => false, 'query_var' => true, 'capability_type' => 'post', 'rest_base' => 'posts' ); register_post_type('archive', $args); } //это чтобы было удобнее писать описание к фоточкам add_action('admin_head', 'gallery_custom_css'); function gallery_custom_css(){ echo ' '; } //сохраняем количество символов в посте function add_post_charcount( $post_id ) { $content = get_post_field( 'post_content', $post_id ); // Get the content $charcount = strlen( strip_tags( $content ) ); // Count the words if ( ! add_post_meta( $post_id, '_post_content_length', $charcount, true ) ) { update_post_meta( $post_id, '_post_content_length', $charcount ); } } add_action( 'save_post', 'add_post_charcount' ); add_action( 'post_updated', 'add_post_charcount' ); //счетчик символов add_filter('mce_external_plugins', 'my_tinymce_plugins'); function my_tinymce_plugins($plugins_array) { $plugins_array = array( //'charactercount' => get_template_directory_uri()."/assets/js/admin/tinymce.plugin.charcount.js" 'charactercount' => get_template_directory_uri() . "/assets/js/admin/tinymce.plugin.charcount.js" ); return $plugins_array; } function admin_script() { wp_enqueue_script('thickbox'); wp_enqueue_style('thickbox'); } add_action( 'admin_enqueue_scripts', 'admin_script' ); //оформление счетчика символов! function admin_style() { if(is_user_logged_in()){ wp_enqueue_style('admin-styles', get_template_directory_uri().'/assets/css/admin/app.css'); } } add_action('admin_enqueue_scripts', 'admin_style'); add_action('wp_enqueue_scripts', 'admin_style'); add_action('admin_footer', 'my_admin_footer'); function my_admin_footer() { get_template_part('admin', 'footer'); } add_action('admin_head', 'my_admin_header'); function my_admin_header() { get_template_part('admin', 'header'); } add_action( 'init', 'hide_revisions' ); function hide_revisions(){ if(filter_input(INPUT_GET,'revision',FILTER_VALIDATE_INT) != 0 && !current_user_can('administrator') && !current_user_can('corrector') && !current_user_can('chief_editor')){ wp_die('Страница не существует. Проверьте URL адрес страницы или обратитесь к администратору.'); } } add_action('admin_footer', 'hide_revisions_style'); function hide_revisions_style() { if (!current_user_can('administrator') && !current_user_can('corrector') && !current_user_can('chief_editor')){ echo ''; } } add_action('admin_footer', 'check_content_layout'); function check_content_layout() { if(get_current_user_id() == 1){return;} if (get_current_user_id() == 53) { //echo ''; //return; } echo << document.forms.post.onsubmit = function(e) { var content; if(tinymce.activeEditor == null){ content = document.forms.post.elements.content.value; }else{ content = (tinymce.activeEditor.getContent() !== '') ? tinymce.activeEditor.getContent() : document.forms.post.elements.content.value; } if(findTags('span:not(.mce_SELRES_start):not(.mce-preview-object):not(.mce-object-iframe):not(.mce-shim):not(.anchor)',content) !== 0 || !checkUnslosedTags(content)){ console.log('Есть спаны или незакрытые теги'); alert('Вставленный текст не может быть сохранен и опубликован из-за нарушения требований безопасности сайта. Вставка осуществляется ТОЛЬКО в режиме «Текст»'); return false; }else{ console.log('Все ок'); } } function findTags(selector,input) { var htmlObject = document.createElement('div'); htmlObject.innerHTML = input; var elems = htmlObject.querySelectorAll(selector); console.log(htmlObject); console.log(elems.length+' - Результат поиска спанов'); if (elems.length !== 0){ console.log(elems); } return elems.length; } function isSelfClosingTag(tagName) { return tagName.match(/area|base|br|col|embed|hr|img|input|keygen|link|menuitem|meta|param|source|track|wbr|script/i); } function checkUnslosedTags(input){ var tags = []; jQuery.each(input.split('\\n'), function (i, line) { jQuery.each(line.match(/<[^>]*[^/]>/g) || [], function (j, tag) { var matches = tag.match(/<\/?([a-z0-9]+)/i); if (matches) { tags.push({tag: tag, name: matches[1], line: i+1, closing: tag[1] == '/'}); } }); }); if (tags.length == 0) { console.log("Текст чист, неплохо!)"); return true; } var openTags = []; var error = false; var indent = 0; for (var i = 0; i < tags.length; i++) { var tag = tags[i]; if (tag.closing) { var closingTag = tag; if (isSelfClosingTag(closingTag.name)) { continue; } if (openTags.length == 0) { console.log("Незакрытых тегов нет! Отлично!"); return true; } var openTag = openTags[openTags.length - 1]; if (closingTag.name != openTag.name) { console.log('Закрывающий тег ' + closingTag.tag + ' в строке ' + closingTag.line + ' не соответствует открывающему ' + openTag.tag + ' в строке ' + openTag.line + '.'); return false; } else { openTags.pop(); } } else { var openTag = tag; if (isSelfClosingTag(openTag.name)) { continue; } openTags.push(openTag); } } if (openTags.length > 0) { var openTag = openTags[openTags.length - 1]; console.log('Открывающий тег ' + openTag.tag + ' в строке ' + openTag.line + ' не имеет закрывающего тега.'); return false; } console.log('Ладно, все окей'); return true; } EOL; } //фикс вывода авторов в фиде add_filter( 'the_author', 'zen_real_author' ); function zen_real_author( $display_name ){ if (is_feed()){ return implode(", ", array_map(function($a){return $a->display_name;}, get_coauthors())); } return $display_name; } //если есть подзаголовок, то в фиде для Дзена выведется он //условие с id убрать где-нибудь через полгодика add_filter( 'the_title_rss', 'subtitle_as_title_for_zen' ); function subtitle_as_title_for_zen( $title ) { if (has_secondary_title() && is_feed() && get_query_var('feed') == 'zen' && in_array(get_post_type(),array('profile_article'))){ $title = get_secondary_title(); } if (has_secondary_title() && is_feed() && get_query_var('feed') == 'googlenews' ){ //$title = get_secondary_title(); } return $title; } add_filter( 'the_title', 'subtitle_as_title_for_googlenews', 10, 2 ); function subtitle_as_title_for_googlenews( $title, $id ) { if (has_secondary_title($id) && is_feed() && get_query_var('feed') == 'googlenews'){ $title = get_secondary_title($id); } return $title; } //отсюда add_action( 'wp_ajax_wpse_139269_inline_edit_radio_checked_hack', 'wpse_139269_inline_edit_radio_checked_hack' ); add_action( 'wp_ajax_nopriv_wpse_139269_inline_edit_radio_checked_hack', 'wpse_139269_inline_edit_radio_checked_hack' ); function wpse_139269_inline_edit_radio_checked_hack() { $terms = wp_get_object_terms( $_POST[ 'ajax-post-id' ], $_POST[ 'ajax-taxonomy' ], array( 'fields' => 'ids' ) ); $result = $terms[0]; echo json_encode($result); exit; die(); } add_action( 'admin_enqueue_scripts', 'wpse_139269_inline_edit_radio_checked_hack_enqueue_script' ); function wpse_139269_inline_edit_radio_checked_hack_enqueue_script() { wp_enqueue_script( 'editphp-inline-edit-tax-radio-hack-js', get_template_directory_uri() . '/assets/js/admin/editphp-inline-edit-tax-radio-hack.js', array( 'jquery' ) ); } add_action( 'wp_ajax_inline-save', 'wpse_139269_wp_ajax_inline_save', 0 ); function wpse_139269_wp_ajax_inline_save() { global $wp_list_table; check_ajax_referer( 'inlineeditnonce', '_inline_edit' ); if ( ! isset($_POST['post_ID']) || ! ( $post_ID = (int) $_POST['post_ID'] ) ) wp_die(); if ( 'page' == $_POST['post_type'] ) { if ( ! current_user_can( 'edit_page', $post_ID ) ) wp_die( __( 'You are not allowed to edit this page.' ) ); } else { if ( ! current_user_can( 'edit_post', $post_ID ) ) wp_die( __( 'You are not allowed to edit this post.' ) ); } if ( $last = wp_check_post_lock( $post_ID ) ) { $last_user = get_userdata( $last ); $last_user_name = $last_user ? $last_user->display_name : __( 'Someone' ); printf( $_POST['post_type'] == 'page' ? __( 'Saving is disabled: %s is currently editing this page.' ) : __( 'Saving is disabled: %s is currently editing this post.' ), esc_html( $last_user_name ) ); wp_die(); } $data = &$_POST; $post = get_post( $post_ID, ARRAY_A ); // Since it's coming from the database. $post = wp_slash($post); $data['content'] = $post['post_content']; $data['excerpt'] = $post['post_excerpt']; // Rename. $data['user_ID'] = get_current_user_id(); if ( isset($data['post_parent']) ) $data['parent_id'] = $data['post_parent']; // Status. if ( isset($data['keep_private']) && 'private' == $data['keep_private'] ) $data['post_status'] = 'private'; else $data['post_status'] = $data['_status']; if ( empty($data['comment_status']) ) $data['comment_status'] = 'closed'; if ( empty($data['ping_status']) ) $data['ping_status'] = 'closed'; // Exclude terms from taxonomies that are not supposed to appear in Quick Edit. if ( ! empty( $data['tax_input'] ) ) { foreach ( $data['tax_input'] as $taxonomy => $terms ) { $tax_object = get_taxonomy( $taxonomy ); if ( ! apply_filters( 'quick_edit_show_taxonomy', $tax_object->show_in_quick_edit, $taxonomy, $post['post_type'] ) ) { unset( $data['tax_input'][ $taxonomy ] ); } } } // Hack: wp_unique_post_slug() doesn't work for drafts, so we will fake that our post is published. if ( ! empty( $data['post_name'] ) && in_array( $post['post_status'], array( 'draft', 'pending' ) ) ) { $post['post_status'] = 'publish'; $data['post_name'] = wp_unique_post_slug( $data['post_name'], $post['ID'], $post['post_status'], $post['post_type'], $post['post_parent'] ); } // Update the post. edit_post(); $wp_list_table = _get_list_table( 'WP_Posts_List_Table', array( 'screen' => $_POST['screen'] ) ); $level = 0; $request_post = array( get_post( $_POST['post_ID'] ) ); $parent = $request_post[0]->post_parent; while ( $parent > 0 ) { $parent_post = get_post( $parent ); $parent = $parent_post->post_parent; $level++; } $wp_list_table->display_rows( array( get_post( $_POST['post_ID'] ) ), $level ); if( $_POST['post_type'] == 'profile_article' || $_POST['post_type'] == 'anew' || $_POST['post_type'] == 'yellow') { ?> '; $content .= 'Скрыть через'; $content .= ''; $content .= ' дней'; $content .= ''; return $content; } /*function show_thumbnail(){ $days = ((get_post_meta(get_the_ID(),'_hide_thumbnail_countdown'))[0]); if ( $days == NULL ){ return true; } $days = (int)$days; if ((((date("U") - get_the_date("U")) > 86400*$days && $days >= 0) && count(get_post_meta(get_the_ID(),'_hide_thumbnail_countdown')) !== 0) || $days == 0 ){ return false; } return true; }*/ //проверка наличия роли у пользователя function user_has_role($user_id, $role){ $user = get_user_by("id",$user_id); if (!is_object($user)){ return false; } foreach ($user->roles as $r){ if ($r === $role){ return true; } return false; } } function hide_publishing_actions(){ global $post; $authors = array_map(function($el){return $el->ID;},get_coauthors()); if( is_object($post) && ( ($post->post_type == 'profile_article' || $post->post_type == 'anew' || $post->post_type == 'yellow') && (!current_user_can('administrator')) && (get_current_user_id() != $post->post_author) && (!in_array(get_current_user_id(),$authors)) && (!user_has_role(get_current_user_id(),'managing_editor')) && (!user_has_role(get_current_user_id(),'chief_editor')) && (!user_has_role(get_current_user_id(),'newsline_editor')) && (!user_has_role(get_current_user_id(),'senior_editor')) && (!user_has_role(get_current_user_id(),'corrector')) ) || user_has_role(get_current_user_id(),'editor') ){ echo ' '; } } add_action('admin_head', 'hide_publishing_actions'); /*if(!function_exists('display_php_error_for_admin')) { function display_php_error_for_admin() { if(get_current_user_id() == 1){ error_reporting(E_ALL); @ini_set('display_errors', 1); }else{ error_reporting(0); @ini_set('display_errors', 0); } } } add_action('init','display_php_error_for_admin');*/ add_filter( 'amp_post_template_data', function( $data ) { $data['amp_component_scripts'] = array_merge( $data['amp_component_scripts'], array( 'amp-auto-ads' => 'https://cdn.ampproject.org/v0/amp-auto-ads-0.1.js', ) ); return $data; } ); function print_component() { echo ''; } add_action( 'wp_footer', function() { if ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) { print_component(); } } ); function print_amp_counters(){ get_template_part('counters', 'amp'); } add_action( 'amp_post_template_footer', function() { if ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) { print_amp_counters(); } } ); function print_amp_css() { get_template_part('styles', 'amp'); } add_action( 'amp_post_template_css', function() { if ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) { print_amp_css(); } } ); add_filter( 'amp_post_template_data', function( $data ) { $data['amp_component_scripts'] = array_merge( $data['amp_component_scripts'], array( 'amp-auto-ads' => true, ) ); return $data; } ); add_action( 'amp_post_template_footer', 'print_component' ); ####внимание, костыль, который я поправлю потом#### if ( get_current_user_id() != 1 && get_current_user_id() != 2 && get_current_user_id() != 3 && get_current_user_id() != 58 ){ add_action('admin_head', 'gurren_dan_menuitems'); } function gurren_dan_menuitems() { echo ' '; } add_action( 'admin_print_footer_scripts', 'remove_save_button' ); function remove_save_button() { ?> roles, array('administrator', 'editor_in_chief')) || in_array(get_current_user_id(), array(58))) && (isset( $_POST['save'] ) || isset( $_POST['publish'] )) && (get_post_status(get_the_ID()) == "publish" || get_post_status(get_the_ID()) == "future") && !in_array(get_current_user_id(), array(57)) && get_post_type(get_post(get_the_ID())) != 'guest-author' ){ $location = "/?post_type=".get_post_type(get_post(get_the_ID()))."&p=".get_the_ID()."&preview=true"; //debug(get_current_user_id().": ".$location); return $location; } return $location; } function empty_excerpt_more( $more ) { return ''; } add_filter('excerpt_more', 'empty_excerpt_more'); add_action( 'wp_print_styles', 'tj_deregister_yarpp_header_styles' ); function tj_deregister_yarpp_header_styles() { wp_dequeue_style('yarppWidgetCss'); wp_deregister_style('yarppRelatedCss'); } add_action( 'wp_footer', 'tj_deregister_yarpp_footer_styles' ); function tj_deregister_yarpp_footer_styles() { wp_dequeue_style('yarppRelatedCss'); } add_action('admin_head','clear_interface',10); function get_current_user_role_roles() { $user_meta = get_userdata(get_current_user_id()); $roles = $user_meta->roles; return $roles; } function clear_interface() { $roles = get_current_user_role_roles(); $remove = array(); $hide = array(); if (in_array('editor',$roles)){ $remove = array( "amp-options", "tools.php", "profile.php" ); $hide = array( "#visibility-radio-password", "#visibility-radio-password+label", "#visibility-radio-password+label+br", "#visibility-radio-private", "#visibility-radio-private+label", "#visibility-radio-private+label+br", ".misc-pub-section.misc-amp-status" ); } foreach ($remove as $item){ remove_menu_page( $item ); } echo ""; } add_action( 'admin_print_footer_scripts', 'add_title_char_counter' ); function add_title_char_counter(){ $screen = get_current_screen(); if(in_array($screen->id, array('edit-yellow', 'edit-profile_article', 'edit-anew'))) { return; } $script = << jQuery.fn.countChars = function() { let cc = jQuery(this).val().length; let limit = [60,70]; let stop = ["Google уже не поймет", "Теперь не поймет и Яндекс"]; let container = jQuery(this).siblings(".charcount."+jQuery(this).attr('id')); container.find('span').eq(0).html(cc); if (cc > limit[1]) { container.fadeIn(); container.removeClass('danger').addClass('warning').find('span').eq(1).html(stop[1]); } else if (cc > limit[0]) { container.fadeIn(); container.addClass('danger').removeClass('warning').find('span').eq(1).html(stop[0]); } else { container.removeClass('danger').removeClass('warning').find('span').eq(1).html(); container.fadeOut(); } jQuery(container).css({ "top":jQuery(this).position().top+"px" }); } jQuery(document).ready(function(){ setTimeout(function(){ jQuery('input#title').each(function(){ jQuery(this).before('
'+jQuery(this).val().length+'
'); jQuery(this).countChars(); }); },2000); jQuery('#poststuff').on('blur click paste keyup keydown keypress focusin focusout focus','#title',function(e){ jQuery(this).countChars(e); }); }); EOL; if (in_array(get_post_type(),array('anew','yellow'))){ $script .= ""; } echo $script; } /*if (in_array(get_current_user_id(), array(1,37)) ){ echo '
';
    var_dump(get_current_user_role_roles());
    echo '
'; }*/ //метаполя в статье add_action('post_submitbox_misc_actions', 'create_custom_fields_submitbox'); add_action('save_post', 'save_custom_fields'); $fields = array( array(//Скрывает пост с главной "type" => "checkbox", "pt" => array("anew","profile_article"), "metabox" => "submitbox", "id" => "_hide_on_mainpage", "meta_key" => false, "label" => "Не показывать на главной", "value" => "1", "echo" => true, "roles" => false ), array(//Скрывает пост с главной "type" => "checkbox", "pt" => array("anew","profile_article"), "metabox" => "submitbox", "id" => "_hide_on_website", "meta_key" => false, "label" => "Не показывать на сайте", "value" => "1", "echo" => true, "roles" => false ), array(//Доступ только по ссылке, отправка в РСС "type" => "checkbox", "pt" => array("anew","profile_article","yellow"), "metabox" => "submitbox", "id" => "_only_link_access", "meta_key" => false, "label" => "Доступно только по ссылке", "value" => "1", "echo" => true, "roles" => false ), /*array(//Исключить из РСС для Я.Н. и Г.Н. "type" => "checkbox", "pt" => array("anew","profile_article","yellow"), "metabox" => "submitbox", "id" => "layf_exclude_from_feed", "meta_key" => false, "label" => "Исключить из новостных фидов", "value" => "1", "echo" => true, "roles" => false ),*/ array(//Исключить из РСС для Я.Н. "type" => "checkbox", "pt" => array("anew","profile_article","yellow"), "metabox" => "submitbox", "id" => "ynrss_exclude", "meta_key" => false, "label" => "Исключить из ЯН", "value" => "1", "echo" => true, "roles" => false ), array(//Исключить из РСС для Г.Н. "type" => "checkbox", "pt" => array("anew","profile_article","yellow"), "metabox" => "submitbox", "id" => "gnrss_exclude", "meta_key" => false, "label" => "Исключить из GN", "value" => "1", "echo" => true, "roles" => false ), array(//Исключить из РСС для Я.Дзен "type" => "checkbox", "pt" => array("anew","profile_article","yellow"), "metabox" => "submitbox", "id" => "yzrssenabled_meta_value", "meta_key" => false, "label" => "Исключить из Я.Дзен", "value" => array( 0 => "no", 1 => "yes" ), "echo" => true, "roles" => false ), array(//Тематика Я.Дзен "type" => "checkbox", "pt" => array("anew","profile_article"), "metabox" => "submitbox", "id" => "yzcategory_meta_value", "meta_key" => false, "label" => "", "value" => NULL, "echo" => false, "roles" => false ), array(//Событие "type" => "checkbox", "pt" => array("anew","yellow"), "metabox" => "submitbox", "id" => "event", "meta_key" => false, "label" => "Событие", "value" => "1", "echo" => true, "roles" => array( "administrator", "editor_in_chief", "corrector", "newsline_editor", "senior_editor", "chief_editor", "editor" ) ), array( "type" => "date", "pt" => array("anew","yellow"), "metabox" => "submitbox", "id" => "event_date", "meta_key" => false, "label" => "Дата", "echo" => function($post_id){ return (get_post_meta($post_id, 'event', true) == '1') ? true : false; }, "roles" => array( "administrator", "editor_in_chief", "corrector", "chief_editor", "senior_editor", "newsline_editor" ) ), array( "type" => "checkbox", "pt" => array("guest-author"), "metabox" => "author_settings", "id" => "show_data", "meta_key" => false, "label" => "Показывать подробности", "value" => "1", "echo" => true, "roles" => array( "administrator", "editor_in_chief", "chief_editor", "managing_editor" ) ), array( "type" => "checkbox", "pt" => array("guest-author"), "metabox" => "author_settings", "id" => "show_only_articles", "meta_key" => false, "label" => "Показывать только статьи", "value" => "1", "echo" => true, "roles" => array( "administrator", "editor_in_chief", "chief_editor", "managing_editor" ) ), array( "type" => "select", "pt" => array("profile_article"), "metabox" => "columnist_category", "id" => "mt_category", "meta_key" => false, "label" => "", "value" => array( "IT" => "IT", "Авто-мото" => "Авто-мото", "Бизнес и финансы" => "Бизнес и финансы", "В мире животных" => "В мире животных", "Военное дело" => "Военное дело", "Дети и семья" => "Дети и семья", "Дом/Дача" => "Дом/Дача", "Игры" => "Игры", "История" => "История", "Кино" => "Кино", "Кулинария" => "Кулинария", "Культура и искусство" => "Культура и искусство", "Медицина и здоровье" => "Медицина и здоровье", "Мода и красота" => "Мода и красота", "Наука и технологии" => "Наука и технологии", "Общество" => "Общество", "Охота и рыбалка" => "Охота и рыбалка", "Политика" => "Политика", "Работа и карьера" => "Работа и карьера", "Реклама" => "Реклама", "Религия" => "Религия", "Спорт" => "Спорт", "Строительство и недвижимость" => "Строительство и недвижимость", "Туризм" => "Туризм", "Фото" => "Фото", "Шоу-бизнес" => "Шоу-бизнес", "Юмор и развлечения" => "Юмор и развлечения" ), "echo" => true, "roles" => array( "administrator", "editor_in_chief", "chief_editor", "corrector", "senior_editor", "newsline_editor", "editor" ) ), array(//Молния "type" => "checkbox", "pt" => array("anew","yellow"), "metabox" => "submitbox", "id" => "_breaking", "meta_key" => false, "label" => "Молния", "value" => "1", "echo" => true, "roles" => array( "administrator", "editor_in_chief", "chief_editor", "senior_editor", "newsline_editor" ) ), array(//Телега "type" => "checkbox", "pt" => array("anew","profile_article","yellow"), "metabox" => "submitbox", "id" => "_send_telegram", "meta_key" => false, "label" => "Отправить в канал", "after" => function(){ return (get_post_meta(get_the_ID(), '_sended_telegram', true)) ? "(отправлено)" : ""; }, "value" => "1", "echo" => true, "roles" => array( "corrector", "editor_in_chief", "administrator", "chief_editor", "senior_editor", "newsline_editor" ) ), array(//Телега отправлено "type" => "checkbox", "pt" => array("anew","profile_article"), "metabox" => "submitbox", "id" => "_sended_telegram", "meta_key" => false, "label" => "Отправлено в канал", "value" => "1", "echo" => false, "roles" => array( "editor_in_chief", "chief_editor", "administrator", "senior_editor", "newsline_editor" ) ), ); function check_user_meta_access($field){ $allow = false; $user = wp_get_current_user(); if (!is_array($field["roles"])){ return true; } if( array_intersect($field["roles"], $user->roles) || $field["roles"] === false ) { $allow = true; } if (array_key_exists("users", $field)) { if (in_array($user->ID, $field["users"]["allow"])) { $allow = true; } if (in_array($user->ID, $field["users"]["deny"])) { $allow = false; } } return $allow; } function create_custom_fields_submitbox() {//создаем кастомные чекбоксы global $fields; $post_id = get_the_ID(); $post_type = get_post_type(); foreach ($fields as $field) { //hr(check_user_meta_access($field)); if (in_array($post_type,$field["pt"]) && $field['metabox'] == 'submitbox'){ create_custom_field($field); } } } function create_custom_fields($post, $params) {//создаем кастомные чекбоксы global $fields; $post_id = get_the_ID(); $post_type = get_post_type(); foreach ($fields as $field) { //hr(check_user_meta_access($field)); if (in_array($post_type,$field["pt"]) && $field['metabox'] == $params['id']){ create_custom_field($field); } } } function create_custom_field($field) {//создаем кастомный чекбокс global $fields; $post_id = get_the_ID(); $gpm = get_post_meta($post_id, $field['id'], true); foreach ($fields as $f){ if ($f["id"] !== $field["id"]) { continue; } $value = (is_array($f["value"])) ? array_search($gpm,$f["value"]) : $gpm; } $write = (is_callable($field['echo'])) ? $field['echo']($post_id) : $field['echo']; wp_nonce_field('nonce_'.$field['id'].'_'.$post_id, 'nonce_'.$field['id']); if ($write): $display = check_user_meta_access($field) ? "d-block" : "d-none"; ?>
' . _e($field['label']); break; case("checkbox_option"): $html = ' ' . _e($field['label']); break; case('date'): $html = ' ' . _e($field['label']); break; case('select'): $html = ''; break; case('text'): $txt_val = is_closure($field['value']) ? $field['value']() : $field['value']; $html = _e($field['label']) . ''; //$html = ''; break; default: $html = ''; } return $html; } function is_closure($t) { return $t instanceof \Closure; } function save_custom_fields() {//сохраняем кастомные чекбоксы if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return; } global $fields; $post_id = get_the_ID(); foreach ($fields as $field) { save_custom_field($post_id, $field); } } function save_custom_field($post_id, $field) {//сохраняем кастомный чекбокс global $fields; $value = $_POST[$field['id']]; if (is_callable($field["onsave"])){ if(!$field["onsave"]()){ return; } } if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return; } if (!isset($_POST['nonce_'.$field['id']]) || !wp_verify_nonce($_POST['nonce_'.$field['id']], 'nonce_'.$field['id'].'_'.$post_id)) { return; } if (!current_user_can('edit_post', $post_id)) { return; } if (isset($_POST[$field['id']])) { foreach ($fields as $f) { if ($f["id"] !== $field["id"]) { continue; } $value = is_array($f["value"]) ? (isset($_POST[$field['id']])) ? $f["value"][1] : $f["value"][0] : $_POST[$field["id"]]; $field['id'] = ($f['meta_key']) ? $f['meta_key'] : $field['id']; $value = $f['type'] == 'select' ? $_POST[$field['id']] : $value; } update_post_meta($post_id, $field['id'], $value); } else { if ($field['echo'] === true){ delete_post_meta($post_id, $field['id']); } } } add_action( 'add_meta_boxes' , 'remove_post_custom_fields',99 ); function remove_post_custom_fields() {//убираем ненужные мета $context = array('normal','advanced','side'); $screen = array('anew','profile_article','yellow'); $id = array( 'layf_related_links', 'yzen_meta_box' ); foreach ($context as $c){ foreach ($screen as $s){ foreach ($id as $i){ remove_meta_box( $i , $s , $c ); } } } } add_action( 'add_meta_boxes', 'yzen_meta_boxx' ); function yzen_meta_boxx(){//Добавляем свой метабокс для тематик дзена взамен стандартного add_meta_box('yzen_category', 'Тематика Яндекс.Дзен', 'yzen_categories', array('profile_article','anew','yellow'), 'normal' , 'high'); } function yzen_categories(){//создаем селект в своем метабоксе дзена $meta_name = 'yzcategory_meta_value'; $categories = array("Происшествия", "Политика", "Война", "Общество", "Экономика", "Спорт", "Технологии", "Наука", "Игры", "Музыка", "Литература", "Кино", "Культура", "Мода", "Знаменитости", "Психология", "Здоровье", "Авто", "Дом", "Хобби", "Еда", "Дизайн", "Фотографии", "Юмор", "Природа", "Путешествия"); $meta_value = get_post_meta(get_the_ID(),$meta_name,true); $html = ''; $html .= wp_nonce_field('nonce_yzcategory_meta_value_'.get_the_ID(), 'nonce_yzcategory_meta_value'); echo $html; } //добавляем свои колонки в таблицу-список статей add_filter('manage_yellow_posts_columns', 'add_custom_columns'); add_filter('manage_anew_posts_columns', 'add_custom_columns'); add_filter('manage_profile_article_posts_columns', 'add_custom_columns'); function add_custom_columns($columns){ $arr = array('thumb' => 'Фото'); return $columns+$arr; } //добавляем в таблицу содержимое для ячеек кастомных колонок add_action( 'manage_yellow_posts_custom_column', 'add_custom_columns_column'); add_action( 'manage_anew_posts_custom_column', 'add_custom_columns_column'); add_action( 'manage_profile_article_posts_custom_column', 'add_custom_columns_column'); function add_custom_columns_column( $column_name ) { if ($column_name === 'thumb') { if (has_post_thumbnail()) { ?>
]+) height=".*?"/i', '$1', $output); $output = preg_replace('/(<[^>]+) width=".*?"/i', '$1', $output); $output = preg_replace('/(<[^>]+) style=".*?"/i', '$1', $output); return $output; } //упорядочиваем загрузку новостей при бесконечном скролле // убираем ссылку на ленту комментариев для каждого поста function pr_disable_feed() { wp_redirect(get_option('siteurl')); } add_action('do_feed', 'pr_disable_feed', 1); add_action('do_feed_rdf', 'pr_disable_feed', 1); add_action('do_feed_rss', 'pr_disable_feed', 1); add_action('do_feed_rss2', 'pr_disable_feed', 1); add_action('do_feed_atom', 'pr_disable_feed', 1); remove_action( 'wp_head', 'feed_links_extra', 3 ); remove_action( 'wp_head', 'feed_links', 2 ); remove_action( 'wp_head', 'rsd_link' ); //Добавили к ссылкам nofollow add_action( 'after_wp_tiny_mce', function(){ ?> term_id); array_push($ids, $crnt_cat->category_parent); } if (is_home()){ return true; } if (in_array(91781, $ids)){ return true; } foreach ($ids as $id){ if(get_term_meta( $id, 'type', 1 ) == "branding"){ return false; } } return true; } //Удалил лишние колонки из таблицы WP /*add_filter('manage_yellow_posts_columns', 'remove_columns_for_user', 10); add_filter('manage_anew_posts_columns', 'remove_columns_for_user', 10); add_filter('manage_profile_article_posts_columns', 'remove_columns_for_user', 10); add_filter( 'manage_edit-yellow_columns', 'remove_columns_for_user', 10); add_filter( 'manage_edit-anew_columns', 'remove_columns_for_user', 10); add_filter( 'manage_edit-profile_article_columns', 'remove_columns_for_user', 10);*/ function remove_columns_for_user($columns) { /*if (!in_array(get_current_user_id(), array(57, 37))) { return $columns; } $unset = array("secondary_title", "cb", "coauthors", "tags", "comments", "thumb", "wpseo-score", "wpseo-score-readability", "wpseo-title", "wpseo-metadesc", "wpseo-focuskw", "wpseo-links", "wpseo-linked"); foreach ($unset as $key) { //unset($columns[$key]); }*/ return $columns; } add_action( 'admin_head', 'admin_head_styles' ); function admin_head_styles(){ ?> parent == 0) ? $cat[0]->cat_ID : $cat[0]->parent; return $id; } //Добавление дополнительных интервалов в крон add_filter('cron_schedules','my_cron_schedules'); function my_cron_schedules($schedules){ if(!isset($schedules["5min"])){ $schedules["5min"] = array( 'interval' => 5*60, 'display' => __('Once every 5 minutes')); } if(!isset($schedules["2min"])){ $schedules["2min"] = array( 'interval' => 2*60, 'display' => __('Once every 2 minutes')); } if(!isset($schedules["30min"])){ $schedules["30min"] = array( 'interval' => 30*60, 'display' => __('Once every 30 minutes')); } if(!isset($schedules["1min"])){ $schedules["1min"] = array( 'interval' => 1*60, 'display' => __('Once every 1 minute')); } if(!isset($schedules["10sec"])){ $schedules["10sec"] = array( 'interval' => 10, 'display' => __('Once every 10 seconds')); } if(!isset($schedules["1week"])){ $schedules["1week"] = array( 'interval' => 60*60*24*7, 'display' => __('Once every 1 week')); } return $schedules; } //Проверка, выбрана ли рубрика в quick-edit add_action('admin_footer', 'quick_edit_category_required'); function quick_edit_category_required(){ $script = << (function($){ $('.save', $('#inline-edit')).click(function(e){ console.log(e); if(!checkFields(this, $)){ e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); alert('Сначала выберите рубрику!'); } }) })(jQuery); function checkFields(el,$) { var elems = $(el).parents('tr').find('input[name="post_category[]"]:checked, input[name="radio_tax_input[category][]"]:checked'); return (elems.length == 0) ? false : true; } JS; $screen = get_current_screen(); if($screen->base == 'edit'){ echo $script; } } //если создаем новую желтую, надо сразу ее помечать как желтую add_action('admin_footer', 'mark_new_yellow'); function mark_new_yellow(){ $screen = get_current_screen(); if (is_edit_page('new') && $screen->id == 'yellow'){ echo << (function($){ $('input[name="_yellow"]').prop('checked',true); })(jQuery); JS; } } //Фильтр для отсеивания материалов, доступных только по ссылке add_filter( 'posts_where', 'only_link_access_request_filter', 99, 1 ); function only_link_access_request_filter($where){ if (!is_single() && !is_admin() || filter_input(INPUT_GET, 'action') == 'alm_get_posts'){ $where .= " AND `ID` NOT IN (SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = '_only_link_access' and `meta_value` = '1') "; //$where .= " AND '".esc_sql($_SERVER['REQUEST_URI'])."' = '".esc_sql($_SERVER['REQUEST_URI'])."' "; } return $where; } //Фильтр для отсеивания материалов дзен add_filter( 'posts_where', 'only_link_access_request_filter', 99, 1 ); function dzen_request_filter($where){ if(str_contains($_SERVER["REQUEST_URI"], "feed/zen")){ $where .= " AND `ID` NOT IN (SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = 'yzrssenabled_meta_value' and `meta_value` = 'yes') "; } return $where; } add_filter( 'posts_where', 'dzen_request_filter', 99, 1 ); add_filter( 'posts_where', 'hide_on_website_request_filter', 99, 1 ); function hide_on_website_request_filter($where){ if((is_admin() || is_feed() || is_single() || is_yn()) && filter_input(INPUT_GET, 'action') != 'alm_get_posts'){ return $where; }else { $where .= " AND `ID` NOT IN (SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = '_hide_on_website' and `meta_value` = '1') "; } return $where; } //Фильтр для добавления тега милитари в рубрику милитари add_filter( 'posts_where', 'military_posts_appending' ); function military_posts_appending($where){ if((filter_input(INPUT_GET, 'slug') == 'military' || get_queried_object_id() == 8529) && !is_feed()){ $where .= " OR `ID` IN (SELECT `object_id` FROM `wp_term_relationships` WHERE `term_taxonomy_id` = 103464) "; } return $where; } add_filter( 'posts_where', 'persona_posts_appending' ); function persona_posts_appending($where){ if((filter_input(INPUT_GET, 'slug') == 'persona' || get_queried_object_id() == 105049) && !is_feed()){ $where .= " OR `ID` IN (SELECT `object_id` FROM `wp_term_relationships` WHERE `term_taxonomy_id` = 105047) "; } return $where; } //Фильтр для добавления импортозамещение милитари в рубрику "знай наших" add_filter( 'posts_where', 'import_posts_appending' ); function import_posts_appending($where){ if((filter_input(INPUT_GET, 'slug') == 'znaj-nashih' || get_queried_object_id() == 104807) && !is_feed() && !is_admin()){ //$where .= " OR (`ID` IN (SELECT `object_id` FROM `wp_term_relationships` WHERE `term_taxonomy_id` = 17548) AND `post_status` = 'publish' AND `ID` NOT IN (SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = '_hide_on_website' and `meta_value` = '1') ) "; $where .= " AND ID != 1067204 OR (`post_status` = 'publish' AND `ID` IN (SELECT `object_id` FROM `wp_term_relationships` WHERE `term_taxonomy_id` = 17548 AND `object_id` NOT IN (SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = '_hide_on_website' and `meta_value` = '1') ) )"; } return $where; } //Фильтр для отсеивания на главной публикаций с чеком "Не показывать на главной" add_action ('posts_where', 'mainpage_request_filter'); function mainpage_request_filter($where){ if (is_home() || filter_input(INPUT_GET, 'id') == 'home_page'){ $where .= " AND `ID` NOT IN (SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = '_hide_on_mainpage' and `meta_value` = '1') "; } return $where; } add_action ('posts_where', function($where){ if (filter_input(INPUT_GET, 'id') == 'mainpage_request'){ $where .= " AND `ID` NOT IN (".implode(",", json_decode(get_option('mainpage_ids'))).") "; } return $where; },999,1); //Фильтр для отсеивания в рекомендациях публикаций с чеком "Не показывать в рекомендуемом" add_filter('posts_where', 'related_request_filter', 10, 2); function related_request_filter($where, $wp_query) { global $wpdb; if(!mb_strrpos($wpdb->last_query,'yarpp')){ return $where; } $where .= " AND `ID` NOT IN (SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = '_hide_from_related' AND `meta_value` = '1') AND `post_type` "; return $where; } //Фильтр для отсеивания из фида Дзена публикаций с чеком "Не отправлять в Дзен" add_filter( 'posts_where', 'zen_feed_request_filter', 10, 2 ); function zen_feed_request_filter($where, $query){ //$yzen_options = get_option('yzen_options'); //if (array_values(array_filter(explode('/', esc_sql($_SERVER['REQUEST_URI']))))[1] == $yzen_options['yzrssname'] && $query->query['posts_per_page'] == $yzen_options['yznumber']){ if(is_zen() && is_feed()){ $where = " AND `wp_posts`.`ID` NOT IN (SELECT `post_id` FROM `wp_postmeta` where `meta_key` = 'yzrssenabled_meta_value' AND `meta_value` = 'yes' ) "; $where .= " AND `ID` IN (SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = '_thumbnail_id') "; $where .= " AND `post_type` IN ('anew','profile_article','yellow') "; $where .= " AND ( ( wp_posts.post_status = 'publish' ) ) "; } return $where; } //Фильтр для фида избранных материалов add_filter( 'posts_where', 'featured_feed_request_filter', 10, 2 ); function featured_feed_request_filter($where, $query){ if(array_key_exists('feed',$query->query)){ if ($query->query['feed'] == get_option('ff_options', false)['url']){ $where .= " AND `ID` IN (SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = 'featured_teaser') "; } } return $where; } add_filter( 'wpseo_canonical', 'prefix_filter_canonical_example' ); function prefix_filter_canonical_example( $canonical ) { if( strpos(filter_input(INPUT_SERVER, 'REQUEST_URI'), '/events/') === false || strlen(str_replace('events','',preg_replace('/[0-9\-\/]/', '', filter_input(INPUT_SERVER, 'REQUEST_URI')))) !== 0 ) { return $canonical; } else { $canonical = 'https://profile.ru/events/'; } return $canonical; } function filter_by_the_author() { $params = array( 'name' => 'author', // this is the "name" attribute for filter '; } add_action( 'restrict_manage_posts', 'legolas_add_taxonomy_filters' ); function datesort_add_default_filter(){ echo ''; echo ''; } add_action( 'restrict_manage_posts', 'datesort_add_default_filter' ); //Кобзев не загружает картинки больше 500КБ (хотя и это слишком много) add_filter('upload_size_limit', 'upload_size_lim', 10, 3); function upload_size_lim($size, $u_bytes, $p_bytes){ if (in_array(get_current_user_id(), array(17))){ $size = 512000; } return $size; } //Ресайз фреймов с врезами add_filter( 'the_content', 'responsive_embeds' ); function responsive_embeds( $content ) { $content = str_replace('sandbox="allow-scripts"', 'sandbox="allow-same-origin allow-top-navigation allow-scripts"', $content); return $content; } //Отключили сжатие картинок add_filter( 'jpeg_quality', function( $quality ){ return 100; }); //Настройки автора! function author_settings_meta_box() { $screens = array( 'guest-author' ); foreach ( $screens as $screen ) { add_meta_box( 'author_settings', __( 'Настройки', 'author_settings' ), 'create_custom_fields', $screen ); } } add_action( 'add_meta_boxes', 'author_settings_meta_box' ); add_filter('layf_content_feed', 'remove_blockquotes'); function remove_blockquotes($content){ $content = preg_replace('~~Usi', "", $content); return $content; } add_filter('the_content', 'remove_blockquotes_from_feed'); function remove_blockquotes_from_feed($content){ if(is_feed()) { $content = preg_replace('~~Usi', "", $content); $content = preg_replace('~