Files
profile/garbage-functions.php

2337 lines
92 KiB
PHP
Raw Permalink Normal View History

2025-07-09 21:21:17 +03:00
<?php
/*
add_action('future_to_publish', 'ttteeesssttt', 10, 1);
function ttteeesssttt($post_id){
debug("qweqweqwe");
}
$mobile_partners = array(
"pulse-mobile" => 50,
"smi2-mobile" => 50
);
$chance_mobile_partners = chance($mobile_partners);
if ( ! function_exists( 'profilemagazine_setup' ) ) :
function profilemagazine_setup() {
if(get_current_user_id() == 1){
//ini_set('display_errors',1);error_reporting(E_ERROR);
}
set_post_thumbnail_size( 782, 440, true );
//создаем зоны меню
register_nav_menus( array(
'header_menu' => __( 'Меню в шапке', 'profilemagazine' ),
'burger_menu_1' => __( 'Меню в бургере 1', 'profilemagazine' ),
'burger_menu_2' => __( 'Меню в бургере 2', 'profilemagazine' ),
'footer_menu_1' => __( 'Меню в подвале 1', 'profilemagazine' ),
'footer_menu_2' => __( 'Меню в подвале 2', 'profilemagazine' ),
'footer_menu_3' => __( 'Меню в подвале 3', 'profilemagazine' ),
) );
add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' );
//настраиваем классы и обертки для меню
function my_wp_nav_menu_args( $args='' ) {
$args['container'] = 'div';
$args['container_class'] = 'float-xs-none float-md-left';
$args['menu_class'] = 'nav d-block d-md-flex';
return $args;
}
add_theme_support( 'html5', array(
'search-form', 'comment-form', 'comment-list', 'gallery', 'caption'
) );
//форматы материалов, в будущем допилить вывод галерей
add_theme_support(
'post-formats',
array(
'aside', 'image', 'video', 'quote', 'link', 'gallery', 'status', 'audio', 'chat'
)
);
add_editor_style( array( 'css/editor-style.css', 'genericons/genericons.css') );
add_theme_support( 'customize-selective-refresh-widgets' );
add_theme_support( 'post-thumbnails', array( 'post', 'profile_article', 'anew', 'bwg_gallery', 'guest-author', 'yellow' ) );
}
endif;
//зоны для виджетов
function profilemagazine_widgets_init() {
// для новостей
register_sidebar( array(
'name' => __( 'Левый сайдбар', 'profilemagazine' ),
'id' => 'left_sidebar',
'description' => __( 'Запихните сюда что-нибудь, чтобы оно появилось на сайте', 'profilemagazine' ),
'before_widget' => '',
'after_widget' => '',
'before_title' => '',
'after_title' => '',
) );
// для поиска
register_sidebar( array(
'name' => __( 'Площадка для поиска', 'profilemagazine' ),
'id' => 'search_sidebar',
'description' => __( 'Запихните сюда что-нибудь, чтобы оно появилось на сайте', 'profilemagazine' ),
'before_widget' => '',
'after_widget' => '',
'before_title' => '',
'after_title' => '',
) );
//для баннера или двух материалов справа
register_sidebar( array(
'name' => __( 'Правый сайдбар', 'profilemagazine' ),
'id' => 'right_sidebar',
'description' => __( 'Запихните сюда что-нибудь, чтобы оно появилось на сайте', 'profilemagazine' ),
'before_widget' => '',
'after_widget' => '',
'before_title' => '',
'after_title' => '',
) );
//для верхнего большого баннера
register_sidebar( array(
'name' => __( 'Верхний сайдбар', 'profilemagazine' ),
'id' => 'top_sidebar',
'description' => __( 'Запихните сюда что-нибудь, чтобы оно появилось на сайте', 'profilemagazine' ),
'before_widget' => '',
'after_widget' => '',
'before_title' => '',
'after_title' => '',
) );
}
add_action( 'widgets_init', 'profilemagazine_widgets_init' );
function profilemagazine_javascript_detection() {
echo "<script>(function(html){html.className = html.className.replace(/\bno-js\b/,'js')})(document.documentElement);</script>\n";
}
add_action( 'wp_head', 'profilemagazine_javascript_detection', 0 );
//add_filter('posts_where', 'remove_breaking_from_feed',10,1);
function remove_breaking_from_feed($where) {
if(is_yn() || is_zen()) {
$where .= " AND `wp_posts`.`ID` NOT IN (SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = '_breaking' AND `meta_value` = '1') ";
}
return $where;
}
function profilemagazine_resource_hints( $urls, $relation_type ) {
if ( wp_style_is( 'profilemagazine-fonts', 'queue' ) && 'preconnect' === $relation_type ) {
if ( version_compare( $GLOBALS['wp_version'], '4.7-alpha', '>=' ) ) {
$urls[] = array(
'href' => 'https://fonts.gstatic.com',
'crossorigin',
);
} else {
$urls[] = 'https://fonts.gstatic.com';
}
}
return $urls;
}
add_filter('wp_resource_hints', 'profilemagazine_resource_hints', 10, 2);
//верстка формы поиска
function profilemagazine_search_form_modify( ) {
ob_start();
?>
<form class="searchform d-block d-sm-block d-lg-block" action="/" method="GET">
<button class="searchform__btn" type="submit">
<svg viewBox="0 0 24 25" class="align-baseline svg-icon">
<use xlink:href="/wp-content/themes/profile/assets/img/sprites-svg/dist/sprite.svg#lens"></use>
</svg>
<svg viewBox="0 0 24 25" class="align-baseline svg-icon">
<use xlink:href="/wp-content/themes/profile/assets/img/sprites-svg/dist/sprite.svg#lens-white"></use>
</svg>
</button>
<input name="s" type="search" placeholder="Поиск по сайту">
</form>
<?php
$html = ob_get_clean();
return $html;
}
add_filter( 'get_search_form', 'profilemagazine_search_form_modify' );
//инициализация параметров для регистрации типов постов
function article_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' => false,
'supports' => array( 'title', 'subtitle', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ),
'taxonomies' => array('post_tag','category'),
'rewrite' => array('slug' => '','with_front' => true),
'can_export' => true,
'show_in_menu' => true,
'menu_position' => 5,
'show_in_nav_menus' => true,
'publicly_queryable' => true,
'exclude_from_search' => false,
'query_var' => true,
'capability_type' => 'post',
'rest_base' => 'posts',
'yarpp_support' => true
);
register_post_type('profile_article', $args);
}
add_action( 'init', 'article_register_post_type_init' );
//регистрация статей в качестве типа постов
add_filter( 'post_updated_messages', 'anew_post_type_messages' );
function anew_post_type_messages( $messages ) {
global $post, $post_ID;
$messages['functions'] = array( // functions - название созданного нами типа записей
0 => '', // Данный индекс не используется.
1 => sprintf( 'Новость обновлена. <a href="%s">Просмотр</a>', esc_url( get_permalink($post_ID) ) ),
2 => 'Параметр обновлён.',
3 => 'Параметр удалён.',
4 => 'Новость обновлена',
5 => isset($_GET['revision']) ? sprintf( 'Новость восстановлена из редакции: %s', wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
6 => sprintf( 'Новость опубликована на сайте. <a href="%s">Просмотр</a>', esc_url( get_permalink($post_ID) ) ),
7 => 'Новость сохранена.',
8 => sprintf( 'Отправлено на проверку. <a target="_blank" href="%s">Просмотр</a>', esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
9 => sprintf( 'Запланировано на публикацию: <strong>%1$s</strong>. <a target="_blank" href="%2$s">Просмотр</a>', date_i18n( __( 'M j, Y @ G:i' ), strtotime( $post->post_date ) ), esc_url( get_permalink($post_ID) ) ),
10 => sprintf( 'Черновик обновлён. <a target="_blank" href="%s">Просмотр</a>', esc_url( add_query_arg( 'preview', 'true', get_permalink($post_ID) ) ) ),
);
return $messages;
}
//Проверка, на новом мы посте или нет
function is_edit_page($new_edit = null) {
global $pagenow;
if (!is_admin()) return false;
if($new_edit == "edit")
return in_array( $pagenow, array( 'post.php', ) );
elseif($new_edit == "new") //check for new post page
return in_array( $pagenow, array( 'post-new.php' ) );
else //check for either new or edit
return in_array( $pagenow, array( 'post.php', 'post-new.php' ) );
}
//Редиректим Артемку со списка желтухи в список новостей
//add_action('current_screen', 'hide_yellow_list');
function hide_yellow_list() {
$screen = get_current_screen();
if ($screen->id == 'edit-yellow' && in_array(get_current_user_id(), array(17))) {
wp_redirect('/wp-admin/edit.php?post_type=anew');
}
if (is_edit_page('new') && in_array(get_current_user_id(), array(17)) && $screen->id == 'yellow') {
wp_redirect('/wp-admin/post-new.php?post_type=anew');
}
}
//add_action('admin_head', 'hide_news_for_yellow');
function hide_news_for_yellow() {
$screen = get_current_screen();
if (!in_array(get_current_user_id(), array(17))){ return; }
if ($screen->id == 'yellow') {
echo '<style>#menu-posts-anew{display:none;}</style>';
} else {
echo '<style>#menu-posts-yellow{display:none;}</style>';
}
echo '<style>#last-edit{display:none!important;}</style>';
}
////
//регистрация желтухи в качестве типа материала
add_action('init', 'yellow_register_post_type_init');
function yellow_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,
'menu_position' => 6,
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ),
'taxonomies' => array('post_tag','category'),
'rewrite' => array('slug' => 'gregator','with_front' => false),
'query_var' => true,
'capability_type' => 'post',
'rest_base' => 'posts',
'publicly_queryable' => true,
'exclude_from_search' => false,
'yarpp_support' => true
);
register_post_type('yellow', $args);
}
//регистрация новостей в качестве типа постов
add_action( 'init', 'anew_register_post_type_init' );
function anew_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,
'menu_position' => 6,
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ),
'taxonomies' => array('post_tag','category'),
'rewrite' => array('slug' => 'news','with_front' => true),
'query_var' => true,
'capability_type' => 'post',
'rest_base' => 'posts',
'publicly_queryable' => true,
'exclude_from_search' => false,
'yarpp_support' => true
);
register_post_type('anew', $args);
}
//виджет новостей
//add_action( 'widgets_init', 'profileNewsWidget_register_widget' );
//виджет для баннера, куда надо запихать только номер зоны
class profileBannerWidget extends WP_Widget {
function __construct() {
parent::__construct('profileBannerWidget',__('Баннер', 'Profile_Magazine'),array( 'description' => __( 'Баннер', 'Profile_Magazine' ), ));
}
public function widget( $args, $instance )
{
$adfoxDate = date("U");
$the_sidebars = wp_get_sidebars_widgets();
$bCount = count($the_sidebars['right_sidebar']);
$cell = ($bCount == 1) ? 'cell cell--double' : 'cell';
$html = '';
if ($args['id'] == 'right_sidebar' && !wp_is_mobile()):
if(test_ad()){
$html = '
<div class="cell special__multi special--gray" id="AdwolfBanner264x558_173300" style="max-height:558px;" ></div>
<script type="text/javascript" >
new Adwolf({
placeholderId: \'AdwolfBanner264x558_173300\',
width: 264,
height: 558,
link: \'https://a.adwolf.ru/3145/prepareCode?pp=bl&ps=cmm&p2=km&pct=a&plp=a&pli=a&pop=a&pr=\'}, {puids:{}}, {paps:{}}, {});
</script>
';
}else{
if (!defined('MAX_PATH')) {
define('MAX_PATH', '/var/www/revive');
}
if (@include_once(MAX_PATH . '/www/delivery/alocal.php')) {
if (!isset($phpAds_context)) {
$phpAds_context = array();
}
if(in_array(get_current_user_id(), array(1,4))) {
$phpAds_raw = view_local('', 1, 0, 0, '', '', '0', $phpAds_context, '');
//$phpAds_raw['html'] = str_replace('bannerid', 'bvar', $phpAds_raw['html']);
//$phpAds_raw['html'] = str_replace('clickTag', 'ctvar', $phpAds_raw['html']);
//$phpAds_raw['html'] = str_replace('advert', 'somestring3', $phpAds_raw['html']);
//$phpAds_raw['html'] = str_replace('campaign', 'somestring4', $phpAds_raw['html']);
//$phpAds_raw['html'] = str_replace('zoneid', 'somestring5', $phpAds_raw['html']);
//$phpAds_raw['html'] = str_replace('delivery', 'dfolder', $phpAds_raw['html']);
} else {
$phpAds_raw = view_local('', 1, 0, 0, '', '', '0', $phpAds_context, '');
//$phpAds_raw['html'] = str_replace('bannerid', 'bvar', $phpAds_raw['html']);
//$phpAds_raw['html'] = str_replace('clickTag', 'ctvar', $phpAds_raw['html']);
//$phpAds_raw['html'] = str_replace('advert', 'somestring3', $phpAds_raw['html']);
//$phpAds_raw['html'] = str_replace('campaign', 'somestring4', $phpAds_raw['html']);
//$phpAds_raw['html'] = str_replace('zoneid', 'somestring5', $phpAds_raw['html']);
//$phpAds_raw['html'] = str_replace('delivery', 'dfolder', $phpAds_raw['html']);
}
$html .= "\t\t" . '<div class="special--main special--gray cell cell--double justify-content-center align-items-center">';
$html .= $phpAds_raw['html'];
$html .= "\t\t" . '</div>';
//$html .= "\t\t" . '</div>';
}
}
//
//$html .= "\t\t".'<div class="special--main special--gray d-flex cell justify-content-center align-items-center">';
//$html .= $phpAds_raw['html'];
//$html .= "<div id=\"adfox_158101195510596829\"></div><script>window.Ya.adfoxCode.create({ownerId: 242477,containerId: 'adfox_158101195510596829',params: {p1: 'ciwcr',p2: 'fpld'}});</script>";
//$html .= "\t\t".'</div>';
$randomvariable = '';//это говно потом убрать при случае
//ира "забыла", блять... забыла она
if (1==2 && !is_post_type_archive() && get_query_var('is_event') != 'true' && (in_array(get_current_page_category(), array(3360, 3365, 3368, 3366, 3367)) || (in_array(wp_get_post_categories(get_queried_object_id())[0], array(3360, 3365, 3368, 3366, 3367)) && is_single()))){
//большой баннер 33
$html .= '<!-----------------';
$html .= wp_get_post_categories(get_queried_object_id())[0];
$html .= '------------------>';
if (!defined('MAX_PATH')){define('MAX_PATH', '/var/www/revive');}
if (@include_once(MAX_PATH . '/www/delivery/alocal.php')) {
if (!isset($phpAds_context)) {
$phpAds_context = array();
}
$phpAds_raw = view_local('', 33, 0, 0, '', '', '0', $phpAds_context, '');
}
$html .= "\t\t".'<div class="special--main special--gray d-flex cell cell--double justify-content-center align-items-center">';
$html .= $phpAds_raw['html'];
$html .= "\t\t".'</div>';
} else {
//два маленьких баннера 49 и 50уче
}
elseif ($args['id'] == 'top_sidebar' && 1==2):
$html .= "\t".'<div class="container-fluid d-none d-md-flex justify-content-center align-items-center">';
$html .= "\t\t".'<div class="special--main d-flex justify-content-center">';
$html .= "\t\t\t".'<!-- Revive Adserver Asynchronous JS Tag - Generated with Revive Adserver v4.1.4 -->';
$html .= "\t\t\t".'<ins data-revive-zoneid="'.$instance['zoneid'].'" data-revive-id="718f7b71460f581846c13b5d8d70857b"></ins>';
$html .= "\t\t\t".'<script async src="//banner.profile.ru/www/delivery/asyncjs.php"></script>';
$html .= "\t\t".'</div>';
$html .= "\t".'</div>';
endif;
echo $html;
}
public function form( $instance ) {
$zoneid = ( isset( $instance[ 'zoneid' ] ) ) ? $instance[ 'zoneid' ] : __( '', 'profileBannerWidget' );
?>
<p>
<label for="<?php echo $this->get_field_id( 'zoneid' ); ?>"><?php _e( 'Номер зоны:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'zoneid' ); ?>" type="text" value="<?php echo esc_attr( $zoneid ); ?>" />
</p>
<?php
}
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['zoneid'] = ( ! empty( $new_instance['zoneid'] ) ) ? strip_tags( $new_instance['zoneid'] ) : '';
return $instance;
}
}
function profileBannerWidget_register_widget() {
register_widget( 'profileBannerWidget' );
}
add_action( 'widgets_init', 'profileBannerWidget_register_widget' );
function header_menu_1(){
$first = (!is_post_type_archive()) ? '<li class="nav-item d-inline-block d-md-none"><a class="nav-link nav-link--feedback" href="/news/">Новости</a></li>' : '';
$args = array(
'menu' => '', // (string) Название выводимого меню (указывается в админке при создании меню, приоритетнее
// чем указанное местоположение theme_location - если указано, то параметр theme_location игнорируется)
'container' => 'div', // (string) Контейнер меню. Обворачиватель ul. Указывается тег контейнера (по умолчанию в тег div)
'container_class' => '', // (string) class контейнера (div тега)
'container_id' => '', // (string) id контейнера (div тега)
'menu_class' => 'nav d-block d-md-flex', // (string) class самого меню (ul тега)
'menu_id' => '', // (string) id самого меню (ul тега)
'echo' => true, // (boolean) Выводить на экран или возвращать для обработки
'fallback_cb' => '', // (string) Используемая (резервная) функция, если меню не существует (не удалось получить)
'before' => '', // (string) Текст перед <a> каждой ссылки
'after' => '', // (string) Текст после </a> каждой ссылки
'link_before' => '', // (string) Текст перед анкором (текстом) ссылки
'link_after' => '', // (string) Текст после анкора (текста) ссылки
'depth' => 0, // (integer) Глубина вложенности (0 - неограничена, 2 - двухуровневое меню)
'walker' => new Child_Wrap, // (object) Класс собирающий меню. Default: new Walker_Nav_Menu
'theme_location' => 'header_menu_1', // (string) Расположение меню в шаблоне. (указывается ключ которым было зарегистрировано меню в функции register_nav_menus)
'items_wrap' => '<ul id="menu-levoe-menyu" class="nav d-block d-md-flex">'.$first.'%3$s</ul>'
);
return wp_nav_menu( $args );
}
function main_menu_classes($classes, $item, $args) {
if($args->theme_location == 'header_menu_1') {
$classes[] = 'nav-item';
}
return $classes;
}
add_filter('nav_menu_css_class', 'main_menu_classes', 1, 3);
function main_submenu_classes($classes, $item, $args) {
if($args->theme_location == 'header_menu_1' && $item->menu_item_parent != 0) {
$classes = [];
}
return $classes;
}
add_filter( 'wp_nav_menu_objects', 'add_has_children_to_nav_items' );
function new_nav_menu_link_attributes( $atts, $item, $args ) {
if($args->theme_location == 'header_menu_1') {
$color = get_term_meta($item->object_id,'color',1);
if($item->menu_item_parent == 0){
$atts['class'] = "nav-link nav-link--{$color}";
}else{
$atts['class'] = "rubric__link";
}
if ($item->current || $item->current_item_ancestor || $item->current_item_parent){
$atts['class'] .= ' active';
}
}
return $atts;
}
add_filter( 'nav_menu_link_attributes', 'new_nav_menu_link_attributes', 10, 3 );
class Child_Wrap extends Walker_Nav_Menu{
function start_lvl(&$output, $depth = 0, $args = array())
{
$indent = str_repeat("\t", $depth);
$output .= "\n$indent<div class=\"subnav__wrapper\"><ul class=\"d-none d-lg-block subnav\">\n";
}
function end_lvl(&$output, $depth = 0, $args = array())
{
$indent = str_repeat("\t", $depth);
$output .= "$indent</ul></div>\n";
}
}
add_filter( 'walker_nav_menu_start_el', 'filter_function_name_2880', 10, 4 );
function filter_function_name_2880( $item_output, $item, $depth, $args ){
return $item_output;
}
//Верстка правого меню
function header_menu_2() {
$menu_name = 'header_menu_2';
if (($locations = get_nav_menu_locations()) && isset($locations[$menu_name])) {
$menu = wp_get_nav_menu_object($locations[$menu_name]);
$menu_items = wp_get_nav_menu_items($menu->term_id);
//манипуляции с названием меню для правильного отсечения по последнему пробелу
preg_match('/([\w*\W]*)\s(.*)$/', $menu->name, $mn);
unset($mn[0]);
$mn = array_values($mn);
$menu_list = "\t\t\t\t". '<ul class="rubric">' ."\n";
$menu_list .= "\t\t\t\t\t". '<li><span class="rubric__direct"><i></i>'.'<span class="d-inline-block d-sm-inline-block d-md-none d-xl-inline-block">'.$mn[0].'&nbsp;</span>'.$mn[1].'</span>' ."\n";
$menu_list .= "\t\t\t\t\t\t". '<ul>' ."\n";
foreach ((array) $menu_items as $key => $menu_item) {
$title = $menu_item->title;
$url = $menu_item->url;
$current = ( $menu_item->object_id == get_queried_object_id() ) ? ' active ' : '';
$menu_list .= "\t\t\t\t\t". '<li><a class="rubric__link" href="'. $url .'">'. $title .'</a></li>' ."\n";
}
$menu_list .= "\t\t\t\t\t\t". '</ul>' ."\n";
$menu_list .= "\t\t\t\t\t". '</li>' ."\n";
$menu_list .= "\t\t\t\t". '</ul>' ."\n";
}
echo $menu_list;
}
//Верстка скрытого меню для мобилок - шапка
function header_menu_3(){
$menu_name = 'header_menu_3';
if (($locations = get_nav_menu_locations()) && isset($locations[$menu_name])) {
$menu = wp_get_nav_menu_object($locations[$menu_name]);
$menu_items = wp_get_nav_menu_items($menu->term_id);
$menu_list = "\t\t\t\t". '<ul class="nav nav__light d-block d-md-none">' ."\n";
foreach ((array) $menu_items as $key => $menu_item) {
$title = $menu_item->title;
$url = $menu_item->url;
$current = ( $menu_item->object_id == get_queried_object_id() ) ? ' active ' : '';
$menu_list .= "\t\t\t\t\t". '<li class="nav-item"><a class="nav-link" href="'. $url .'">'. $title .'</a></li>' ."\n";
}
$menu_list .= "\t\t\t\t". '</ul>' ."\n";
}
echo $menu_list;
}
//Верстка первого и второго меню в подвале
function footer_menu($menu_name){
if (($locations = get_nav_menu_locations()) && isset($locations[$menu_name])) {
$menu = wp_get_nav_menu_object($locations[$menu_name]);
$menu_items = wp_get_nav_menu_items($menu->term_id);
$menu_list = "\t\t\t\t". '<ul class="nav d-block d-md-flex">' ."\n";
foreach ((array) $menu_items as $key => $menu_item) {
$title = $menu_item->title;
$url = $menu_item->url;
$current = ( $menu_item->object_id == get_queried_object_id() ) ? ' active ' : '';
$menu_list .= "\t\t\t\t\t". '<li class="nav-item"><a class="nav-link" href="'. $url .'">'. $title .'</a></li>' ."\n";
}
ob_start();
dynamic_sidebar( 'search_sidebar' );
$search = ob_get_clean();
$menu_list .= '<li class="nav-item">'.$search.'</li>';
$menu_list .= "\t\t\t\t". '</ul>' ."\n";
}
echo $menu_list;
}
//Верстка третьего меню в подвале
function footer_menu_3(){
$menu_name = 'footer_menu_3';
if (($locations = get_nav_menu_locations()) && isset($locations[$menu_name])) {
$menu = wp_get_nav_menu_object($locations[$menu_name]);
$menu_items = wp_get_nav_menu_items($menu->term_id);
$menu_list .= "\t\t\t\t". '<div class="d-block d-md-none">' ."\n";
foreach ((array) $menu_items as $key => $menu_item) {
$title = $menu_item->title;
$url = $menu_item->url;
$menu_list .= "\t\t\t\t\t". '<p><a href="'. $url .'">'. $title .'</a></p>' ."\n";
}
$menu_list .= "\t\t\t\t". '</div>' ."\n";
}
echo $menu_list;
}
//Хуевая альфа версия виджета избранных материалов для главной
class profileRecentPostsWidget extends WP_Widget {
function __construct() {
parent::__construct('profileRecentPostsWidget',__('Избранные материалы', 'Profile_Magazine'),array( 'description' => __( 'Пока альфа, просто введем ИД', 'Profile_Magazine' ), ));
}
public function widget( $args, $instance ) {
foreach ($instance as $postID):
$post = get_post((int)$postID);
$cat = array_shift(get_the_category($postID));
$html = "\t".'<div class="col-12 col-md-4 col-xl-3 float-left">';
$html .= "\t\t".'<div class="article cell">';
$html .= "\t\t\t".'<a class="article__frame" href="'.get_permalink($post).'">';
$html .= "\t\t\t\t".'<img loading="lazy" class="d-block" src="'.wp_get_attachment_url( get_post_thumbnail_id($post), 'thumbnail' ).'" alt="'. get_the_title($postID).'">';
$html .= "\t\t\t\t".'<span class="sticker sticker--'.get_term_meta($cat->term_id,'color',1).'">'.$cat->name.'</span>';
$html .= "\t\t\t".'</a>';
$html .= "\t\t\t".'<div class="article__body">';
$html .= "\t\t\t\t".'<a class="article__title" href="'.get_permalink($post).'">'. get_the_title($postID).'</a>';
$html .= "\t\t\t\t".'<div class="article__detail">';
$html .= "\t\t\t\t\t".'<time datetime="'.get_the_date('Y-m-d H:s').'" class="article__data">'. get_the_date('d.m.Y',$post).'</time>';
foreach (get_coauthors($postID) as $author ):
$html .= "\t\t\t\t\t".'<a class="article__author" href="'.get_author_posts_url( $author->ID, $author->user_nicename ).'">'.$author->display_name.'</a>';
endforeach;
$html .= "\t\t\t\t".'</div>';
$html .= "\t\t\t".'</div>';
$html .= "\t\t".'</div>';
$html .= "\t".'</div>';
echo $html;
endforeach;
}
public function form( $instance ) {
$first = ( isset( $instance[ 'first' ] ) ) ? $instance[ 'first' ] : __( '', 'profileRecentPostsWidget' );
$second = ( isset( $instance[ 'second' ] ) ) ? $instance[ 'second' ] : __( '', 'profileRecentPostsWidget' );
?>
<p>
<label for="<?php echo $this->get_field_id( 'first' ); ?>"><?php _e( 'ИД Первого поста:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'first' ); ?>" type="post" value="<?php echo esc_attr( $first ); ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id( 'second' ); ?>"><?php _e( 'ИД второго поста:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'second' ); ?>" type="post" value="<?php echo esc_attr( $second ); ?>" />
</p>
<?php
}
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['first'] = ( ! empty( $new_instance['first'] ) ) ? strip_tags( $new_instance['first'] ) : '';
$instance['second'] = ( ! empty( $new_instance['second'] ) ) ? strip_tags( $new_instance['second'] ) : '';
return $instance;
}
}
//регистрируем виджеты
function profileRecentPostsWidget_register_widget() {
register_widget( 'profileRecentPostsWidget' );
}
add_action( 'widgets_init', 'profileRecentPostsWidget_register_widget' );
//колорпикер
add_action( 'admin_enqueue_scripts', 'add_color_picker' );
function add_color_picker( $hook ) {
if( is_admin() ) {
wp_enqueue_script( 'wp-color-picker' );
wp_enqueue_style( 'wp-color-picker' );
// Include our custom jQuery file with WordPress Color Picker dependency
wp_enqueue_script( 'custom-script-handle', '/wp-content/themes/profile/assets/js/admin/app.js', false, true );
}
}
//произвольные поля в категории
$taxname = 'category';
add_action("{$taxname}_add_form_fields", 'add_new_custom_fields');
add_action("{$taxname}_edit_form_fields", 'edit_new_custom_fields');
add_action("create_{$taxname}", 'save_custom_taxonomy_meta');
//add_action("edited_{$taxname}", 'save_custom_taxonomy_meta');
//редактирование кастомных полей в категории
function edit_new_custom_fields( $term ) {
global $colors;
global $termTaxTypes;
?>
<tr class="form-field">
<th scope="row" valign="top"><label>Тип</label></th>
<td>
<select name="extra[type]">
<?php foreach ($termTaxTypes as $key => $val): ?>
<?php $selected = (esc_attr( get_term_meta( $term->term_id, 'type', 1 ) == $key)) ? " selected " : "" ;?>
<option class="<?php echo $key; ?>" value="<?php echo $key; ?>"<?php echo $selected; ?>><?php echo $val; ?></option>
<?php endforeach; ?>
</select>
</td>
</tr>
<tr class="form-field">
<th scope="row" valign="top"><label for="extra-calendar">Показывать календарь</label></th>
<td>
<input value="1" name="extra[calendar]" id="extra-calendar" type="checkbox" <?php echo (esc_attr( get_term_meta( $term->term_id, 'calendar', true ) == 1)) ? " checked " : "" ;?> />
</td>
</tr>
<tr class="form-field">
<th scope="row" valign="top"><label>Цвет заголовка</label></th>
<td>
<select name="extra[color]">
<?php foreach ($colors as $key => $val): ?>
<?php $selected = (esc_attr( get_term_meta( $term->term_id, 'color', 1 ) == $key)) ? " selected " : "" ;?>
<option class="<?php echo $key; ?>" value="<?php echo $key; ?>"<?php echo $selected; ?>><?php echo $val; ?></option>
<?php endforeach; ?>
</select>
<span class="description">Цвет заголовка и пункта меню для категории</span>
</td>
</tr>
<tr class="form-field">
<th scope="row" valign="top"><label>Цвет фона</label></th>
<td>
<input class="color-picker" type="text" name="extra[bgcolor]" value="<?php echo esc_attr( get_term_meta( $term->term_id, 'bgcolor', 1 )); ?>" />
<span class="description">Цвет фона тела сайта</span>
</td>
</tr>
<tr class="form-field">
<th scope="row" valign="top"><label>Подзаголовок</label></th>
<td>
<?php
$args = array(
'wpautop' => 1,
'media_buttons' => 1,
'textarea_name' => 'extra[subtitle]', //нужно указывать!
'textarea_rows' => 20,
'tabindex' => null,
'editor_css' => '',
'editor_class' => 'large-text',
'teeny' => 0,
'dfw' => 0,
'tinymce' => 1,
'quicktags' => 1,
'drag_drop_upload' => false
);
wp_editor(html_entity_decode(esc_attr( get_term_meta( $term->term_id, 'subtitle', 1 ))), 'subtitle',$args);
?>
<span class="description">Подзаголовок</span>
</td>
</tr>
<tr class="form-field">
<th scope="row" valign="top"><label>Ссылка с картинки</label></th>
<td>
<input type="text" name="extra[link]" value="<?php echo esc_attr( get_term_meta( $term->term_id, 'link', 1 )); ?>" />
<br/>
<span class="description">Ссылка с картинки</span>
</td>
</tr>
<tr class="form-field">
<th scope="row" valign="top"><label>Текст над заголовком</label></th>
<td>
<input type="text" name="extra[suptitle]" value="<?php echo esc_attr( get_term_meta( $term->term_id, 'suptitle', 1 )); ?>" />
<br/>
<span class="description">Текст над заголовком</span>
</td>
</tr>
<?php
}
//добавление кастомных полей для категории
function add_new_custom_fields( $taxonomy_slug ){
global $colors;
global $termTaxTypes;
?>
<div class="form-field">
<label for="tag-color">Тип</label>
<select name="extra[type]">
<?php foreach ($termTaxTypes as $key => $val): ?>
<option class="<?php echo $key; ?>" value="<?php echo $key; ?>"><?php echo $val; ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-field">
<label for="tag-color">Цвет заголовка</label>
<select name="extra[color]">
<?php foreach ($colors as $key => $val): ?>
<option class="<?php echo $key; ?>" value="<?php echo $key; ?>"><?php echo $val; ?></option>
<?php endforeach; ?>
</select>
<p>Цвет заголовка и пункта меню для категории</p>
</div>
<div class="form-field">
<label for="tag-color">Цвет фона</label>
<input class="color-picker" type="text" name="extra[bgcolor]" value="" />
<p>Цвет фона тела сайта</p>
</div>
<div class="form-field">
<label for="tag-color">Подзаголовок</label>
<?php
$args = array(
'wpautop' => 1,
'media_buttons' => 1,
'textarea_name' => 'extra[subtitle]', //нужно указывать!
'textarea_rows' => 20,
'tabindex' => null,
'editor_css' => '',
'editor_class' => 'large-text',
'teeny' => 0,
'dfw' => 0,
'tinymce' => 1,
'quicktags' => 1,
'drag_drop_upload' => false
);
wp_editor('', 'subtitle',$args);
?>
<p>Подзаголовок</p>
</div>
<div class="form-field">
<label for="tag-color">Ссылка с картинки</label>
<input type="text" name="extra[link]" />
<p>Ссылка с картинки</p>
</div>
<?php
}
//сохранение кастомных полей для категории
function save_custom_taxonomy_meta( $term_id ) {
if ( ! isset($_POST['extra']) ) return;
if ( ! current_user_can('edit_term', $term_id) ) return;
if (
! wp_verify_nonce( $_POST['_wpnonce'], "update-tag_$term_id" ) && // wp_nonce_field( 'update-tag_' . $tag_ID );
! wp_verify_nonce( $_POST['_wpnonce_add-tag'], "add-tag" ) // wp_nonce_field('add-tag', '_wpnonce_add-tag');
) return;
$extra = wp_unslash($_POST['extra']);
foreach( $extra as $key => $val ){
$_key = sanitize_key( $key );
if( $_key !== $key ) wp_die( 'bad key'. esc_html($key) );
if( ! $val ) {
delete_term_meta( $term_id, $_key );
} else {
update_term_meta( $term_id, $_key, $val );
}
}
foreach (get_term_meta($term_id) as $key => $val){
if (!array_key_exists($key, $extra)){
delete_term_meta( $term_id, $key );
}
}
return $term_id;
}
//перенос css
add_action( 'wp_enqueue_scripts', 'enqueue_theme_css' );
function enqueue_theme_css() {
$ver = date("U");
wp_enqueue_style('style', get_stylesheet_directory_uri() . '/assets/css/app.css', array(), $ver);
wp_enqueue_style('d-style', get_stylesheet_directory_uri() . '/assets/css/app-desktop.css', array(), $ver);
if(wp_is_mobile()) {
wp_enqueue_style('m-style', get_stylesheet_directory_uri() . '/assets/css/app-mobile.css', array(), $ver, "(max-width: 992px)");
}
}
//скрываем кнопку загрузки на главной и страницах категории
function my_custom_alm_before_button() {
//return '<style>.alm-load-more-btn.done{display:none!important;}#ajax-load-more{clear:both;}</style>';
}
add_filter( 'alm_before_button', 'my_custom_alm_before_button' );
//логи запросов к БД//
add_filter('posts_where', 'log_user_activity',999,1);
function log_user_activity($where){
$log = $_SERVER['REQUEST_URI'];
if($log == ''){
$log = __FILE__;
}
$log = htmlspecialchars($log);
$log = esc_sql($log);
$where .= " AND '".$log."' = '".$log."' ";
return $where;
}
//обработка и вывод результатов поиска
function search_content_highlight() {
$delta = 200;
$content = html_entity_decode((strip_shortcodes(strip_tags(get_the_content(), '<span>'))));
$searchquery = (get_search_query()) ? get_search_query() : filter_input(INPUT_GET,'search');
$pos = mb_stripos($content,$searchquery);
if (($pos-$delta) > 10) {
$start = mb_strripos(mb_substr($content,0,($pos-$delta)), ' ');
$length = mb_strripos(mb_substr($content,0,($pos+$delta)), ' ')-mb_strripos(mb_substr($content,0,($pos-$delta)), ' ');
$out = '...'.mb_substr($content, ($start), ($length)).'...';
}else{
$length = mb_strripos(mb_substr($content,0,($delta*2)), ' ');
$out = mb_substr($content, 0, $length).'...';
}
$keys = explode(" ",$searchquery);
//$out = mb_ereg_replace('~(?!<.*)(?<!\w)('.implode('|',$keys).')(?!\w|[^<>]*>)~i', '<span class="highlight">\0</span>', $out);
//$out = preg_replace('/('.implode('|', $keys) .')/iu', '<span class="highlight">\0</span>', $out);
$out = strip_tags($out, '<span>');
echo $out;
}
add_action( 'pre_get_posts', 'mainpage_post_query' );
function mainpage_post_query( $query ) {
if ( $query->is_front_page() && $query->is_main_query() && !is_admin() && is_home() ) {
global $wpdb;
if(get_current_user_id() == 1) {
}
//$fst = [1029577,1027344,1025689,1029299,1026533,1025392,1026673,1028622,1028545];
$fst = json_decode(get_option('mainpage_ids'));
$query->set('posts_per_page',10);
$query->set('post_type', array('profile_article', 'anew'));
$query->set('post_status', 'publish');
$query->set('ignore_sticky_posts', 1);
$query->set('post__in',$fst);
$query->set('orderby','FIELD(ID,'.implode(',', $fst).')');
}
return $query;
}
add_filter('posts_orderby', 'main_orderby',10,2 );
function main_orderby( $orderby, $query ){
if ( $query->is_front_page() && $query->is_main_query() && !is_admin() && is_home() ) {
$orderby = $query->query_vars['orderby'];
}
return $orderby;
}
//выпадающий список категорий
add_shortcode( 'my_cat_list', 'my_list_categories_shortcode' );
function my_list_categories_shortcode() {
$list = explode('|',wp_list_categories(
array(
'separator' => '|',
'style'=>'',
'echo'=>false,
'depth'=>0
)
)
);
//echo "<!--";
//var_dump($list);
//echo "-->";
$out = '<select name="category" class="js-nice-select">';
$out .= '<option value="all">Все рубрики</option>';
foreach ($list as $item){
preg_match_all('~<a(.*?)href="([^"]+)"(.*?)>~', $item, $link);
$alias = array_pop(array_diff(explode('/', $link[0][0]),array('','">')));
$name = strip_tags($item);
$active = (get_query_var('category') == $alias) ? ' selected ' : '';
$out .= ($alias != '') ? '<option value="'.$alias.'"'.$active.'>'.$name.'</option>' : '';
}
$out .= '</select>';
echo $out;
}
//выпадающий список периодов для поиска
add_shortcode( 'my_period_list', 'my_list_period_shortcode' );
function my_list_period_shortcode() {
$list = array(
'all' => 'За все время',
'7' => 'За последнюю неделю',
'30' => 'За последний месяц',
'90' => 'За последний квартал',
'365' => 'За последний год'
);
$out = '<select name="period" class="js-nice-select">';
foreach ($list as $value => $item){
$active = (get_query_var('period') == $value) ? ' selected ' : '';
$out .= '<option value="'.$value.'"'.$active.'>'.$item.'</option>';
}
$out .= '</select>';
echo $out;
}
//добавляем переменные, которые можно забрать из гета
add_filter('query_vars', 'my_register_query_vars' );
function my_register_query_vars( $vars ) {
$vars[] = 'period';//для периода в поиске
$vars[] = 'category';//для категории в поиске
$vars[] = 'search';//для аякса и отказа от покупки плагина темплейтов
$vars[] = 'id';//для аякса и отказа от покупки плагина темплейтов
return $vars;
}
function bodyclass(){
$classname = "default";
if(!is_branding() && !is_branding_page()){
//$classname .= " new-year ";
}
switch (true){
case(is_home())://главная
$classname .= " page-index";
break;
case(is_post_type_archive())://страница новостей
$classname .= " page-news";
break;
case(is_author())://страница автора
$classname .= " page-author";
break;
case(is_branding())://страница рубрики
$classname .= " branding ";
break;
case(is_category())://страница рубрики
$classname .= " page-category";
break;
case(is_branding_page())://страница брендированной рубрики или спецпроекта
$classname .= " ".get_term_meta(get_queried_object()->term_id,'type',1);
break;
case(is_search())://страница поиска
$classname .= " page-search";
break;
case (is_single() && get_post_format())://страница галереи или другого нестандартного формата материала
$classname .= " page-single page-".get_post_format();
break;
case (is_single() && get_post_type() == 'anew')://страница новости
$classname .= " page-single page-new";
break;
case (is_single() && get_post_type() == 'yellow')://страница новости
$classname .= " page-single page-new";
break;
case (is_single() && get_post_type() == 'profile_article')://страница материала
$classname .= " page-single page-article";
break;
case (is_single() && get_post_type() == 'archive')://страница архивного материала
$classname .= " page-single page-archive";
break;
case(is_single())://статическая страница
$classname .= " page-single";
break;
default:
}
$branding = deny_branding() ? 'branding' : '';
$class = ' class="'.$classname.' '.$branding.'"';
return $class;
}
function is_branding(){
if (is_single()){
$term_list = wp_get_post_terms(get_the_ID(), 'category', ['fields' => 'all']);
foreach($term_list as $term) {
if(get_term_meta($term->term_id,'type',1) == "branding"){
return true;
}
}
}
if (is_archive() && get_term_meta(get_queried_object()->term_id,'type',1) == 'branding'){
return true;
}else if (is_archive() && get_term_meta(get_queried_object()->category_parent,'type',1) == 'branding'){
return true;
}
return false;
}
function has_branding_link(){
if (is_single()){
$term_list = wp_get_post_terms(get_the_ID(), 'category', ['fields' => 'all']);
foreach($term_list as $term) {
if(get_term_meta($term->term_id,'link',1) != ""){
return true;
}
}
}
if (is_archive() && get_term_meta(get_queried_object()->term_id,'link',1) != ''){
return true;
}else if (is_archive() && get_term_meta(get_queried_object()->category_parent,'link',1) != ''){
return true;
}
return false;
}
function get_branding_link(){
if (is_single()){
$term_list = wp_get_post_terms(get_the_ID(), 'category', ['fields' => 'all']);
foreach($term_list as $term) {
if(get_term_meta($term->term_id,'link',1) != ""){
return get_term_meta($term->term_id,'link',1);
}
}
}
if (is_archive() && get_term_meta(get_queried_object()->term_id,'link',1) != ''){
return get_term_meta(get_queried_object()->term_id,'link',1);
}else if (is_archive() && get_term_meta(get_queried_object()->category_parent,'link',1) != ''){
return get_term_meta(get_queried_object()->category_parent,'link',1);
}
return false;
}
//складываем токены подписчиков в БД
add_action( 'wp_ajax_add_subscriber', 'add_subscriber' );
add_action( 'wp_ajax_nopriv_add_subscriber', 'add_subscriber' );
function add_subscriber() {
//проверка на XSS
if( ! wp_verify_nonce( filter_input(INPUT_GET,'nonce'), 'myajax-nonce' ) ) die( 'Stop!');
global $wpdb;
$wpdb->insert(
'wp_subscribers',
array(
'token' => filter_input(INPUT_GET,'token')
)
);
wp_die();
}
function chance($arr){
//$arr = array("a" => 40);
$charr = array();
foreach ($arr as $key => $val){
for ($i = 0; $i < $val; $i++){
array_push($charr, $key);
}
}
return $charr[rand(0,99)];
}
//add_action('load_textdomain', 'rewrite_utm');
function rewrite_utm() {
$items = array(172345);
$id = (int)array_pop(explode("-",parse_url($_SERVER['REQUEST_URI'])['path']));
$get = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
$chance = chance(array(true => 5, false => 95));
if ($chance) {
if (in_array($id, $items) && in_array("utm_referrer", array_keys($get)) && strripos(filter_input(INPUT_GET, 'utm_referrer', FILTER_SANITIZE_STRING), "yandex") !== false){
$newurl = filter_input(INPUT_SERVER, 'REQUEST_SCHEME', FILTER_SANITIZE_STRING)."://".filter_input(INPUT_SERVER, 'HTTP_HOST', FILTER_SANITIZE_STRING).array_shift(explode("?", filter_input(INPUT_SERVER, 'REQUEST_URI')));
header('HTTP/1.1 301 Moved Permanently');
header('Location: '.$newurl);
exit();
}
}
}
function wp_is_phone() {
static $is_mobile;
if ( isset($is_mobile) )
return $is_mobile;
if ( empty($_SERVER['HTTP_USER_AGENT']) ) {
$is_mobile = false;
} elseif (
strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false
|| strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false
|| strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false
|| strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false
|| strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false ) {
$is_mobile = true;
} elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false && strpos($_SERVER['HTTP_USER_AGENT'], 'iPad') == false) {
$is_mobile = true;
} elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'iPad') !== false) {
$is_mobile = false;
} else {
$is_mobile = false;
}
return $is_mobile;
}
//Прячем рубрики от редакторов
//add_action('admin_head', 'hide_categories');
function hide_categories(){
if (!current_user_can('administrator') || in_array(get_current_user_id(), array(58))){
echo "<style>#front-page-warning, #front-static-pages ul, .categorydiv ul.categorychecklist ul, .customlinkdiv ul.categorychecklist ul, .inline-editor ul.cat-checklist ul, .posttypediv ul.categorychecklist ul, .taxonomydiv ul.categorychecklist ul, ul.export-filters{margin-left:0px!important;} li#category-1 > label, li#popular-category-1, li#category-3347 > label, li#popular-category-3347, li#category-3349 > label, li#popular-category-3349, li#category-3350 > label, li#popular-category-3350, li#category-3351 > label, li#popular-category-3351, li#category-3352 > label, li#popular-category-3352, li#category-3355 > label, li#popular-category-3355, li#category-3356 > label, li#popular-category-3356, li#category-3357 > label, li#popular-category-3357, li#category-3359 > label, li#popular-category-3359, li#category-3361 > label, li#popular-category-3361, li#category-3362 > label, li#popular-category-3362, li#category-3363 > label, li#popular-category-3363, li#category-3364 > label, li#popular-category-3364, li#category-3365 > label, li#popular-category-3365, li#category-3366 > label, li#popular-category-3366, li#category-3367 > label, li#popular-category-3367, li#category-3368 > label, li#popular-category-3368, li#category-3370 > label, li#popular-category-3370, li#category-3371 > label, li#popular-category-3371, li#category-3372 > label, li#popular-category-3372, li#category-3373 > label, li#popular-category-3373, li#category-3374 > label, li#popular-category-3374, li#category-3375 > label, li#popular-category-3375, li#category-3376 > label, li#popular-category-3376, li#category-3377 > label, li#popular-category-3377, li#category-3381 > label, li#popular-category-3381, li#category-3382 > label, li#popular-category-3382, li#category-3383 > label, li#popular-category-3383, li#category-3384 > label, li#popular-category-3384, li#category-3387 > label, li#popular-category-3387, li#category-3389 > label, li#popular-category-3389, li#category-3390 > label, li#popular-category-3390, li#category-3392 > label, li#popular-category-3392, li#category-3393 > label, li#popular-category-3393, li#category-3398 > label, li#popular-category-3398, li#category-3401 > label, li#popular-category-3401, li#category-6974 > label, li#popular-category-6974, li#category-8830 > label, li#popular-category-8830, li#category-8844 > label, li#popular-category-8844, li#category-8966 > label, li#popular-category-8966 {display:none!important;}</style>" ;
}
if(
(user_has_role(get_current_user_id(),'newsline_editor')||user_has_role(get_current_user_id(),'senior_editor'))
&&
(
in_array(get_post_type(), array('anew','yellow'))
||
in_array(filter_input(INPUT_GET, 'post_type'), array('anew','yellow'))
)
){
//echo "<style>li#category-8529 > label, li#popular-category-8529{display:none!important;}</style>";
}
}
//Фильтр запроса вторичной загрузки событий на главной странице событий
add_filter( 'posts_where', 'allevents_request_filter' );
function allevents_request_filter($where){
if (filter_input(INPUT_GET, 'id', FILTER_SANITIZE_STRING) !== 'allevents_request') { return $where; }
$where .= " AND `ID` NOT IN ( SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = '_only_link_access' AND `meta_value` = '1' ) AND `ID` IN (SELECT `post_id` FROM wp_postmeta WHERE `meta_key` = 'event' AND `meta_value` = '1') AND `ID` IN (SELECT `post_id` FROM wp_postmeta WHERE `meta_key` = 'event_date' AND STR_TO_DATE(`meta_value`, '%Y-%m-%d') >= CURDATE()) ";
return $where;
}
//Фильтр запросе вторичной загрузки событий на странице даты/месяца/года
add_filter( 'posts_where', 'events_request_filter' );
function events_request_filter($where){
if (filter_input(INPUT_GET, 'id', FILTER_SANITIZE_STRING) !== 'events_request') { return $where; }
$date = explode(':',filter_input(INPUT_GET, 'custom_args'))[1];
$where .= " AND `ID` NOT IN ( SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = '_only_link_access' AND `meta_value` = '1' ) AND id in (SELECT post_id from wp_postmeta where meta_key = 'event_date' AND meta_value regexp '^{$date}')";
return $where;
}
//Фильтр для отсеивания из всех лент, кроме новостных и экспертного мнения, материалов, в которых нет заходного фото
//add_filter( 'posts_where', 'thumbnail_request_filter' );
function thumbnail_request_filter($where){
if(
(
!is_admin()
&&
!is_single()
&&
!is_page()
&&
!is_author()
&&
get_queried_object_id() != 3396
&&
filter_input(INPUT_GET, 'slug') != 'columnist'
&&
!in_array(
filter_input(INPUT_GET, 'id'),
array(
'author_request',
'post_type_archive'
)
)
&&
!is_post_type_archive()
&&
!is_feed()
&&
!is_search()
&&
!is_tag()
&&
!is_yn()
)
||
(
filter_input(INPUT_GET, 'action') == 'alm_get_posts'
&&
filter_input(INPUT_GET, 'slug') != 'columnist'
)
){
$where .= " AND `ID` IN (SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = '_thumbnail_id') ";
}
if(is_yn() || is_feed()){
$where .= " AND (`ID` IN (SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = '_thumbnail_id') OR `post_type` IN ('anew', 'yellow') ) ";
}
if(get_current_user_id() == 1 && 1==2){
echo $GLOBALS['wp_query']->request;
var_dump(is_admin());
var_dump(is_single());
var_dump(is_page());
var_dump(is_author());
var_dump(get_queried_object_id());
var_dump(filter_input(INPUT_GET, 'slug'));
var_dump(is_post_type_archive());
var_dump(is_feed());
var_dump(is_search());
var_dump(is_tag());
var_dump(filter_input(INPUT_GET, 'action'));
}
return $where;
}
//Фильтр для асинхронной подгрузки авторских постов
add_filter('posts_where', 'author_request_filter',10,1);
function author_request_filter($where){
if (filter_input(INPUT_GET, 'id', FILTER_SANITIZE_STRING) != 'author_request') { return $where; }
global $coauthors_plus;
$post_id = filter_input(INPUT_GET, 'post_id', FILTER_SANITIZE_NUMBER_INT);
$only_articles = get_post_meta($post_id, 'show_only_articles', true);
$term_id = $coauthors_plus->get_author_term($coauthors_plus->get_coauthor_by('ID', (string)$post_id))->term_id;
//$user = get_user_by('login', $coauthors_plus->get_coauthor_by('ID', (string)$post_id)->linked_account);
$where = "
AND wp_posts.post_status = 'publish'
AND `ID` NOT IN ( SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = '_only_link_access' AND `meta_value` = '1' )
AND `ID` IN (SELECT `object_id` FROM `wp_term_relationships` WHERE `term_taxonomy_id` = ".$term_id.")
";
if($only_articles){
$where .= " AND wp_posts.post_type in ('profile_article') ";
}else{
$where .= " AND wp_posts.post_type in ('profile_article','anew','yellow') ";
}
return $where;
}
//add_filter('posts_request', 'dump_feed_sql');
function dump_feed_sql($query){
if (get_current_user_id() == 1){
echo "\n\n\n";
echo ($query);
echo "\n\n\n";
die;
}
return $query;
}
function get_last_id(){
//omfg
return;
$args = array(
'post_type' => array(
'anew',
'profile_article',
'yellow'
),
'posts_per_page' => 1,
'order' => 'DESC',
'orderby' => 'ID'
);
$recent_post = get_posts($args);
return $recent_post[0]->ID;
}
add_action('init','events_rewrite');
function events_rewrite(){
//TODO:дописать фильтр, чтобы срабатывало только в нужных рубриках, дописать настройку рубрик в админке
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 true;
} else {
add_rewrite_tag( '%is_event%', '([^&]+)' );
add_rewrite_tag( '%event_year%', '([^&]+)' );
add_rewrite_tag( '%event_month%', '([^&]+)' );
add_rewrite_tag( '%event_day%', '([^&]+)' );
add_rewrite_rule( '^(events)/([^/]*)/([^/]*)/([^/]*)/?', 'index.php?post_type=yellow&is_event=true&event_year=$matches[2]&event_month=$matches[3]&event_day=$matches[4]', 'top' );
add_rewrite_rule( '^(events)/([^/]*)/([^/]*)/?', 'index.php?post_type=yellow&is_event=true&event_year=$matches[2]&event_month=$matches[3]', 'top' );
add_rewrite_rule( '^(events)/([^/]*)/?', 'index.php?post_type=yellow&is_event=true&event_year=$matches[2]', 'top' );
add_rewrite_rule( '^(events)?','index.php?post_type=yellow&is_event=true', 'top' );
}
}
//Отписка
add_action( 'wp_ajax_unsubscribe', 'unsubscribe' );
add_action( 'wp_ajax_nopriv_unsubscribe', 'unsubscribe' );
function unsubscribe() {
global $wpdb;
$token = filter_input(INPUT_GET,'token');
$wpdb->delete(
'wp_mail_subscribers',
array(
'token' => $token
)
);
header("Location: /unsubscribe/");
wp_die();
}
//Подтверждение подписки
add_action( 'wp_ajax_confirm_subscribe', 'confirm_subscribe' );
add_action( 'wp_ajax_nopriv_confirm_subscribe', 'confirm_subscribe' );
function confirm_subscribe() {
global $wpdb;
$token = filter_input(INPUT_GET,'token');
$wpdb->update(
'wp_mail_subscribers',
array(
'confirmed' => 1
),
array(
'token' => $token
)
);
header("Location: /subscribe/");
wp_die();
}
//Подписка
add_action( 'wp_ajax_add_email_subscriber', 'add_email_subscriber' );
add_action( 'wp_ajax_nopriv_add_email_subscriber', 'add_email_subscriber' );
function add_email_subscriber(){
if( ! wp_verify_nonce( filter_input(INPUT_GET,'nonce'), 'myajax-nonce' ) ) die( 'Stop!');
global $wpdb;
$token = md5(filter_input(INPUT_GET,'email')."subscriber");
$email = filter_input(INPUT_GET,'email');
$emails = $wpdb->get_results("
SELECT
`email`
FROM
`wp_mail_subscribers`
WHERE
`email` = '".$email."'
");
if (count($emails) != 0){
wp_die('Этот e-mail уже подписан на рассылку!');
}
$wpdb->insert(
'wp_mail_subscribers',
array(
'token' => $token,
'email' => $email
)
);
$msg = <<<MESSAGE
Для подтверждения подписки на рассылку, перейдите по <a href="https://profile.ru/wp-admin/admin-ajax.php?action=confirm_subscribe&token={$token}">ссылке</a>.
MESSAGE;
$headers = array();
$headers[] = 'Content-type: text/html; charset=utf-8';
wp_mail(
filter_input(INPUT_GET,'email'),
"Подтверждение подписки - profile.ru",
$msg,
$headers
);
wp_die('На ваш e-mail отправлено подтверждение подписки.');
}
add_action( 'after_setup_theme', 'add_thumb_sizes' );
function add_thumb_sizes() {
add_image_size( 'popular-thumb', 264, 172, true );
}
add_action( 'phpmailer_init', 'send_smtp_email' );
function send_smtp_email( $mail ) {
$mail->SMTPDebug = SMTP_DEBUG;
$mail->IsHTML(true);
$mail->CharSet = "text/html; charset=UTF-8;";
$mail->IsSMTP();
$mail->SMTPAuth = true;
$mail->Host = SMTP_HOST;
$mail->Port = SMTP_PORT;
$mail->Username = SMTP_USER;
$mail->Password = SMTP_PASS;
$mail->From = SMTP_FROM;
$mail->FromName = SMTP_FROM_NAME;
$mail->CharSet = 'UTF-8';
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
return $mail;
}
// лента /articles
add_action('pre_get_posts', 'articles_query' ,100 ,1);
function articles_query($query){
if(!is_admin()) {
if (
array_key_exists('category_name', $query->query)
&&
(
explode("/", $query->query['category_name'])[0] == 'articles'
||
explode("/", $query->query_vars['category_name'])[0] == 'articles'
)
) {
$query->queried_object = get_post_type_object('profile_article');
$query->is_post_type_archive = true;
}
}
}
add_filter('posts_where' , 'articles_where', 10, 2);
function articles_where( $where, $query ) {
global $wpdb;
$qObj = get_queried_object();
if(!is_admin()) {
if(is_object($qObj)) {
if (
$qObj->name == 'profile_article'
&&
(
(
explode("/", $query->query['category_name'])[0] == 'articles'
||
explode("/", $query->query_vars['category_name'])[0] == 'articles'
)
||
(
filter_input(INPUT_GET, 'id', FILTER_SANITIZE_STRING) == 'post_type_archive'
)
)
) {
$where = "
AND wp_posts.post_type IN ( 'profile_article' )
AND ( wp_posts.post_status = 'publish' OR wp_posts.post_status = 'acf-disabled' OR wp_posts.post_author = 1 AND wp_posts.post_status = 'private' )
AND '/articles/' = '/articles/'
AND `ID` IN (SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = '_thumbnail_id')
AND `ID` NOT IN (SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = 'hide_longread_archive' AND `meta_value` = 1)
";
}
}
}
return $where;
}
add_filter( 'wp_title', 'articles_title',100 );
function articles_title( $title ) {
global $wp_query;
if(
array_key_exists('category_name', $wp_query->query)
&&
(
explode("/", $wp_query->query['category_name'])[0] == 'articles'
||
explode("/", $wp_query->query_vars['category_name'])[0] == 'articles'
)
) {
$title = 'Журнал "Профиль" свежие авторские статьи на актуальные темы';
}
return $title;
}
function custom_instagram_settings($code, $url, $attr){
if((strpos($code, 'instagr.am') !== false || strpos($code, 'instagram.com') !== false)){ // if instagram embed
$return = preg_replace("@data-instgrm-captioned@", "", $code); // remove caption class
return $return;
}
return $code;
}
//add_filter('embed_handler_html', 'custom_instagram_settings', 20, 3);
//add_filter('embed_oembed_html', 'custom_instagram_settings', 20, 3);
function check_grabber_refer(){
$server = filter_input_array(INPUT_SERVER);
if(!array_key_exists('HTTP_REFERER', $server) || mb_strpos($server['HTTP_REFERER'], 'https://profile.zoid.ru/') === false) {
return false;
}
return true;
}
//add_filter( 'the_editor_content', 'apply_content_from_grabber' );
function apply_content_from_grabber( $content ) {
if(!check_grabber_refer()){return $content;}
$id = filter_input(INPUT_GET, 'reference', FILTER_SANITIZE_NUMBER_INT);
$json = file_get_contents('https://profile.zoid.ru/rewrite/'.$id);
$content = (json_decode($json))->text;
return $content;
}
//add_filter('admin_footer', 'apply_title_from_grabber');
function apply_title_from_grabber(){
if(!check_grabber_refer()){return;}
$id = filter_input(INPUT_GET, 'reference', FILTER_SANITIZE_NUMBER_INT);
$json = file_get_contents('https://profile.zoid.ru/rewrite/'.$id);
echo '
<script>
jQuery("#title").val("'.(json_decode($json))->title.'");
</script>
';
}
//Накрываем фреймы
function oembed_iframe_overrides($html, $url, $attr) {
if(mb_stripos(parse_url($url)['host'], 'profile.ru') !== false){
return $html;
}
else if(mb_stripos(parse_url($url)['host'], 'facebook') !== false ){
$src = "https://www.facebook.com/plugins/post.php?href=".urlencode($url);
$html = '
<div class="wp_embed_cover">
<div id="fb-root"></div>
<script async defer src="https://connect.facebook.net/ru_RU/sdk.js#xfbml=1&version=v3.2"></script>
<div style="position:absolute;z-index:100000001;width:100%;height:100%;left:0;top:0;right:0;bottom:0;"></div>
<div class="fb-post" data-show-text="true" data-href="'.$url.'"></div>
</div>
';
$html = '';
}else if(mb_stripos(parse_url($url)['host'], 'youtu') !== false){
if (parse_url($url)['host'] == 'youtu.be'){
$id = mb_substr(parse_url($url)['path'], 1);
}else{
$params = explode("&", parse_url($url)['query']);
$id = explode("=", $params[0])[1];
unset($params[0]);
if(count($params) != 0){
$otherQueryParams = '&'.implode("&", $params);
}
}
//<div style="position:absolute;z-index:10000000;width:100%;height:100%;left:0;top:0;right:0;bottom:0;"></div>
$html = '
<div class="wp_embed_cover pb-4">
<div class="youtube_container">
<iframe src="https://youtube.com/embed/'.$id.'?feature=oembed'.$otherQueryParams.'" frameborder="0" allowfullscreen class="youtube_video" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"></iframe>
</div>
</div>
';
}else if(mb_stripos(parse_url($url)['host'], 'instagram') !== false){
$html = '';
}else if(mb_stripos(parse_url($url)['host'], 'twitter') !== false || parse_url($url)['host'] == 't.co'){
$html = '';
} else{
}
if ( strpos( $html, "<iframe" ) !== false ) {
return $html;
} else {
return $html;
}
}
add_filter( 'embed_oembed_html', 'oembed_iframe_overrides', 1000, 3);
//add_filter('the_content', 'readmore',100000000);
function readmore($content){
$dom = new DomDocument('1.0', 'utf-8');
libxml_use_internal_errors(true);
$dom->loadHTML('<meta http-equiv="Content-Type" content="charset=utf-8" />'.$content);
$paragraphs = $dom->getElementsByTagName('p');
$has_gallery = mb_stripos($content, 'swiper');
if ($has_gallery === false && get_post_type() == 'profile_article' && !is_feed() && !is_amp_endpoint() && $paragraphs->length > 3 && !in_array(get_queried_object_id(), array(862348, 922082))) {
$content .= '<div class="read-more-wrap text-center">
<span class="read-more-btn">Читать полностью</span>
<span class="read-more-body">(время чтения ' . reading_time($content) . ' )</span>
</div>';
}
if ( (get_post_type() == 'profile_article' && !is_feed() && !is_amp_endpoint() && $paragraphs->length < 3) || in_array(get_queried_object_id(), array(862348, 922082)) || $has_gallery ) {
$content .= '<style>.micromarking[data-post-type="profile_article"]:not(.full)>:not(.read-more-wrap):not(:nth-child(1)):not(:nth-child(2)):not(:nth-child(3)):not(script):not(style), .micromarking[data-post-type="profile_article"]:not(.full)>:not(:nth-child(1)) iframe{display:block;}</style>';
}
return $content;
}
function reading_time($content){
$content = strip_tags($content);
$words_per_minute = "250";
$text_read = round(count(preg_split('/[\s]+/', $content)) / $words_per_minute, 1);
return decl_of_numb(round($text_read), array(" минута", " минуты", " минут"));
}
function decl_of_numb($all_numb, $titles) {
$cases = array(2, 0, 1, 1, 1, 2);
return $all_numb." ".$titles[($all_numb%100>4 && $all_numb%100<20) ? 2 : $cases[min($all_numb%10, 5)]];
}
//add_filter( 'the_content', 'amp_ad_inread',10);
function amp_ad_inread($content){
if ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) {
$ps = explode("\n", $content);
$ps[1] .= '<amp-ad width="320" height="250"
type="adfox"
data-owner-id="242477"
data-adfox-params=\'{
"p1": "cjkrh",
"p2": "fqzb"
}\'>
<div placeholder></div>
<div fallback></div>
</amp-ad>';
$content = implode("<p>", $ps);
}
return $content;
}
function show_counters(){
if(in_array(get_queried_object_id(), array(299591, 300210, 300212, 300215, 300217, 300220, 816928))){
return false;
}
return true;
}
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');
function header_menu(){
$menu_name = 'header_menu';
if (($locations = get_nav_menu_locations()) && isset($locations[$menu_name])) {
$menu = wp_get_nav_menu_object($locations[$menu_name]);
$menu_items = wp_get_nav_menu_items($menu->term_id);
$menu_list = '';
foreach ((array)$menu_items as $key => $menu_item) {
$title = $menu_item->title;
$url = $menu_item->url;
$current = ($menu_item->object_id == get_queried_object_id()) ? ' active ' : '';
$menu_list .= "\t\t\t\t\t" . '<li><a class="rubric__link" href="' . $url . '">' . $title . '</a></li>' . "\n";
}
}
}
function burger_dt_menu($menu_name) {
if (($locations = get_nav_menu_locations()) && isset($locations[$menu_name])) {
$menu = wp_get_nav_menu_object($locations[$menu_name]);
$menu_items = wp_get_nav_menu_items($menu->term_id);
//манипуляции с названием меню для правильного отсечения по последнему пробелу
preg_match('/([\w*\W]*)\s(.*)$/', $menu->name, $mn);
unset($mn[0]);
$mn = array_values($mn);
$menu_list = '<ul class="list-unstyled">';
$parents = wp_list_pluck( $menu_items, 'menu_item_parent');
//echo '<hr/><pre>';var_dump($parents);echo '</pre><hr/>';
foreach ((array) $menu_items as $key => $menu_item) {
if($menu_item->menu_item_parent != 0){
continue;
}
$className = get_post_meta($menu_item->ID, '_menu_item_color', true);
$className = empty($className) ? "black" : $className;
$className .= in_array($menu_item->ID, $parents) ? ' burger-menu--subnav ' : '';
$class = ' class="burger-menu--'.$className.' '.implode(' ', $menu_item->classes).'" ';
$title = $menu_item->title;
$url = $menu_item->url;
$tt = in_array($menu_item->ID, $parents) ? ' data-target="#burger-menu-'.$menu_item->ID.'" class="collapsed" ' : '';
$menu_list .= '<li'.$class.'>';
$menu_list .= '<a href="'.$url.'" '. $tt .' >'. $title .'</a>';
if(in_array($menu_item->ID, $parents)){
$menu_list .= '<ul id="burger-menu-'.$menu_item->ID.'" class="list-unstyled collapse">';
foreach ((array) $menu_items as $sub_menu_item) {
if($sub_menu_item->menu_item_parent == $menu_item->ID){
$menu_list .= '<li>';
$menu_list .= '<a href="'.$sub_menu_item->url.'">'. $sub_menu_item->title .'</a>';
$menu_list .= '</li>';
}
}
$menu_list .= '</ul>';
}
$menu_list .= '</li>';
}
$menu_list .= '</ul>';
}
echo $menu_list;
return true;
}
function burger_mobile_menu($menu_name) {
if (($locations = get_nav_menu_locations()) && isset($locations[$menu_name])) {
$menu = wp_get_nav_menu_object($locations[$menu_name]);
$menu_items = wp_get_nav_menu_items($menu->term_id);
//манипуляции с названием меню для правильного отсечения по последнему пробелу
preg_match('/([\w*\W]*)\s(.*)$/', $menu->name, $mn);
unset($mn[0]);
$mn = array_values($mn);
$menu_list = '<ul class="list-unstyled">';
$parents = wp_list_pluck( $menu_items, 'menu_item_parent');
//echo '<hr/><pre>';var_dump($parents);echo '</pre><hr/>';
foreach ((array) $menu_items as $key => $menu_item) {
if($menu_item->menu_item_parent != 0){
continue;
}
$className = get_post_meta($menu_item->ID, '_menu_item_color', true);
$className = empty($className) ? "black" : $className;
$class = ' class="burger-menu--'.$className.'" ';
$title = $menu_item->title;
$url = $menu_item->url;
$tt = in_array($menu_item->ID, $parents) ? ' data-target="#burger-menu-'.$menu_item->ID.'" data-toggle="collapse" class="collapsed" aria-expanded="false" ' : '';
$menu_list .= '<li'.$class.'>';
$menu_list .= '<a href="'.$url.'" '. $tt .' >'. $title .'</a>';
if(in_array($menu_item->ID, $parents)){
$menu_list .= '<ul id="burger-menu-'.$menu_item->ID.'" class="list-unstyled collapse">';
foreach ((array) $menu_items as $sub_menu_item) {
if($sub_menu_item->menu_item_parent == $menu_item->ID) {
$menu_list .= '<li>';
$menu_list .= '<a href="' . $sub_menu_item->url . '">' . $sub_menu_item->title . '</a>';
$menu_list .= '</li>';
}
}
$menu_list .= '</ul>';
}
$menu_list .= '</li>';
}
$menu_list .= '</ul>';
}
echo $menu_list;
return true;
}
//
function dt_main_menu($menu_name) {
if (($locations = get_nav_menu_locations()) && isset($locations[$menu_name])) {
$menu = wp_get_nav_menu_object($locations[$menu_name]);
$menu_items = wp_get_nav_menu_items($menu->term_id);
//манипуляции с названием меню для правильного отсечения по последнему пробелу
preg_match('/([\w*\W]*)\s(.*)$/', $menu->name, $mn);
unset($mn[0]);
$mn = array_values($mn);
$menu_list = '';
$parents = wp_list_pluck( $menu_items, 'menu_item_parent');
//echo '<hr/><pre>';var_dump($parents);echo '</pre><hr/>';
foreach ((array) $menu_items as $key => $menu_item) {
if($menu_item->menu_item_parent != 0){
continue;
}
$className = get_post_meta($menu_item->ID, '_menu_item_color', true);
$className = empty($className) ? "black" : $className;
$title = $menu_item->title;
$url = $menu_item->url;
$current = ( $menu_item->object_id == get_queried_object_id() ) ? ' active ' : '';
$menu_list .= '<li class="nav-item">';
$menu_list .= '<a class="nav-link nav-link--'. $className .' '. $current .'" href="'. $url .'">'. $title .'</a>';
$menu_list .= '</li>';
}
}
echo $menu_list;
return true;
}
add_action('post_updated', 'k_label', 10, 1 );
add_action('future_to_publish', 'k_label', 10, 1 );
function k_label($post_id){
if(in_array(get_current_user_id(), array(17))){
$post_id = (is_object($post_id)) ? $post_id->ID : $post_id;
update_post_meta($post_id, '_k_label', 1);
//update_post_meta($post_id, '_yoast_wpseo_meta-robots-noindex', 0);
}
}
add_action( 'posts_where', 'k_label_action' );
function k_label_action($where){
if(
!is_category()
&&
!is_single()
&&
!is_author()
&&
!is_admin()
&&
!is_tag()
&&
!is_post_type_archive()
&&
!is_front_page()
&&
filter_input(INPUT_GET, 'action') != 'alm_get_posts'
){
//$where .= " AND `wp_posts`.`ID` NOT IN ( SELECT `wp_postmeta`.`post_id` FROM `wp_postmeta` WHERE `wp_postmeta`.`meta_key` = '_k_label' AND `wp_postmeta`.`meta_value` = '1') ";
}
if((is_feed() || is_yn()) && filter_input(INPUT_GET, 'action') != 'alm_get_posts'){
//$where .= " AND `wp_posts`.`ID` NOT IN ( SELECT `wp_postmeta`.`post_id` FROM `wp_postmeta` WHERE `wp_postmeta`.`meta_key` = '_k_label' AND `wp_postmeta`.`meta_value` = '1') ";
}
return $where;
}
//add_action( 'posts_where', 'single_post_special_request' );
function single_post_special_request($where){
if(filter_input(INPUT_GET, 'id') == 'single_post_special_request'){
//$where .= ' AND ID = 466706 OR ID = 466706 ';
}
return $where;
}
function add_time_toolbar($wp_admin_bar) {
$args = array(
'id' => 'currtime',
'title' => date("d.m.y H:i:s"),
'href' => '#',
);
$wp_admin_bar->add_node($args);
}
add_action('admin_bar_menu', 'add_time_toolbar', 999);
function main_photo_caption( $str ){
$str = str_ireplace('depositphotos.com', '<a target="_blank" href="https://depositphotos.com/">depositphotos.com</a>', $str);
return $str;
}
function share_block($id){
$title = get_the_title($id);
$link = get_permalink($id);
$str = '
<div class="ya-share2__list">
<a rel="noopener" class="ya-share2__item vk" target="_blank" href="https://vk.com/share.php?url='.urlencode($link.'?utm_from=vk_share').'&title='.urlencode($title).'"><span class="ya-share2__badge"><span class="ya-share2__icon"></span></span></a>
<a rel="noopener" class="ya-share2__item twitter" target="_blank" href="https://twitter.com/intent/tweet?text=&'.urlencode($title).'&url='.urlencode($link.'?utm_from=t_share').'"><span class="ya-share2__badge"><span class="ya-share2__icon"></span></span></a>
<a rel="noopener" class="ya-share2__item telegram" target="_blank" href="tg://msg_url?url='.urlencode($link.'?utm_from=tg_share').'&text='.urlencode($title).'"><span class="ya-share2__badge"><span class="ya-share2__icon"></span></span></a>
<a rel="noopener" class="ya-share2__item ok" target="_blank" href="https://connect.ok.ru/offer?url='.urlencode($link.'?utm_from=ok_share').'&title='.urlencode($title).'"><span class="ya-share2__badge"><span class="ya-share2__icon"></span></span></a>
</div>
';
return $str;
}
//add_action( 'pre_get_posts', 'bild_media_filter', 100 );
function bild_media_filter( $query ) {
if(current_user_can('bild') && is_admin() && filter_input(INPUT_GET, 'action') != 'alm_get_posts'){
$query->set('author__in', array(get_current_user_id()));
}
return $query;
}
add_action( 'wp_enqueue_scripts', 'deregister_scripts_for_optimization', 999 );
add_action( 'wp_print_scripts', 'deregister_scripts_for_optimization', 999 );
add_action( 'wp_print_styles', 'deregister_scripts_for_optimization', 999 );
function deregister_scripts_for_optimization() {
if(wp_is_mobile() && is_single() && 3==3){
wp_dequeue_script('ajax-load-more-js');
wp_deregister_script('ajax-load-more-js');
wp_dequeue_script('ajax-load-more');
wp_deregister_script('ajax-load-more');
}
if(!is_search()){
wp_dequeue_style( 'elasticpress-related-posts-block' );
wp_dequeue_style( 'searchterm-highlighting' );
}
if(!is_admin()){
wp_dequeue_style('wp-block-library');
wp_dequeue_style('wp-block-library-theme');
wp_dequeue_style('wc-block-style');
wp_dequeue_style('wpt-twitter-feed');
wp_deregister_style('wpt-twitter-feed');
wp_dequeue_style('wp-block-library-css');
wp_deregister_style('wp-block-library-css');
wp_dequeue_style('ajax-load-more-filters');
wp_dequeue_style('ajax-load-more-layouts');
wp_dequeue_style('ajax-load-more-paging');
wp_deregister_style('ajax-load-more-filters');
wp_deregister_style('ajax-load-more-layouts');
wp_deregister_style('ajax-load-more-paging');
}
if(1==2) {
if (wp_is_mobile() && (is_single() || is_front_page() || is_home() || is_author() || is_category() || is_archive() || is_tag() || is_search() || is_post_type_archive())) {
wp_dequeue_style('wp-block-library');
wp_dequeue_style('wp-block-library-theme');
wp_dequeue_style('wc-block-style');
wp_dequeue_style('wpt-twitter-feed');
wp_deregister_style('wpt-twitter-feed');
wp_dequeue_style('wp-block-library-css');
wp_deregister_style('wp-block-library-css');
//wp_dequeue_script('ajax-load-more-js');
//wp_deregister_script('ajax-load-more-js');
//wp_dequeue_script('ajax-load-more');
//wp_deregister_script('ajax-load-more');
wp_dequeue_script('wp-embed-js');
wp_deregister_script('wp-embed-js');
//wp_deregister_style('ajax-load-more-filters');
//wp_deregister_style('ajax-load-more-layouts');
//wp_deregister_style('ajax-load-more-paging');
}
if (in_array(get_post_type(), array('anew', 'yellow'))) {
wp_dequeue_script('wp-embed-js');
wp_deregister_script('wp-embed-js');
wp_deregister_script('wp-embed');
}
}
}
function posts_to_promote(){
return false;
$posts = [1016041, 1019827, 1019987, 1019928];
return in_array(get_queried_object_id(), $posts);
}
add_action('mainpage_producer_update', 'mainpage_producer_requests');
function mainpage_producer_requests() {
global $wpdb;
$sticky = implode(",", get_option('sticky_posts'));
$first_query = "
SELECT SQL_CALC_FOUND_ROWS DISTINCT
wp_posts.ID
FROM
wp_posts
WHERE
wp_posts.post_type = 'profile_article' AND
wp_posts.post_status = 'publish' AND
wp_posts.ID NOT IN (
SELECT post_id FROM wp_postmeta WHERE meta_key = '_hide_on_mainpage' AND meta_value = '1'
) AND
wp_posts.ID NOT IN (
SELECT object_id FROM wp_term_relationships where term_taxonomy_id = 3396
) AND
wp_posts.ID IN (
SELECT post_id FROM wp_postmeta WHERE meta_key = '_thumbnail_id'
) AND
wp_posts.ID NOT IN (
SELECT post_id FROM wp_postmeta WHERE meta_key = '_only_link_access'
) AND
wp_posts.ID IN (" . $sticky . ")
GROUP BY
wp_posts.ID
ORDER BY
wp_posts.post_date DESC
LIMIT 0,1";
$first = $wpdb->get_results($first_query)[0]->ID;
//$first = 1265356;
$second_query = "
SELECT SQL_CALC_FOUND_ROWS DISTINCT
wp_posts.ID
FROM
wp_posts
WHERE
wp_posts.ID IN (" . $sticky . ") AND
wp_posts.post_type = 'profile_article' AND
wp_posts.post_status = 'publish' AND
wp_posts.ID NOT IN (
SELECT post_id FROM wp_postmeta WHERE meta_key = '_only_link_access'
) AND
wp_posts.ID NOT IN (
SELECT post_id FROM wp_postmeta WHERE meta_key = '_hide_on_mainpage' AND meta_value = '1'
) AND
wp_posts.ID != ".((int)$first)."
GROUP BY
wp_posts.ID
ORDER BY
wp_posts.post_date DESC
LIMIT 0, 1";
$second = $wpdb->get_results($second_query)[0]->ID;
$second = 1341019;
$fs = array($first, $second);
$third_query = "
SELECT SQL_CALC_FOUND_ROWS DISTINCT
wp_posts.ID
FROM
wp_posts
WHERE
wp_posts.ID NOT IN ( " . implode(",", $fs) . " ) AND
wp_posts.post_type = 'profile_article' AND
wp_posts.ID IN (
SELECT post_id FROM wp_postmeta WHERE meta_key = '_thumbnail_id'
) AND
wp_posts.ID NOT IN (
SELECT post_id FROM wp_postmeta WHERE meta_key = '_only_link_access'
) AND
wp_posts.post_status = 'publish' AND
wp_posts.ID NOT IN ( SELECT post_id FROM wp_postmeta WHERE meta_key = '_hide_on_mainpage' AND meta_value = '1' )
GROUP BY
wp_posts.ID
ORDER BY
wp_posts.post_date DESC
LIMIT 0,7";
$third = array_map(function ($obj) {
return $obj->ID;
}, $wpdb->get_results($third_query));
$fst = array_merge($fs, $third);
update_option('mainpage_ids', json_encode($fst));
if ( defined( 'WP_CLI' ) && WP_CLI ) {
debug("option_updated");
}
}
*/