Files
vij/functions.php
2024-04-04 21:44:28 +03:00

869 lines
20 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
use PHPMailer\PHPMailer\PHPMailer;
//setlocale(LC_ALL, 'ru_RU', 'ru_RU.UTF-8', 'ru', 'russian');
define('IMGURL', 'http://img.vetandlife.ru/');
define("COOK_GOLOS", "_ya_id_76577_w");
define("COOK_VALUE", "7896");
define('VIJ_CACHE', ABSPATH.'wp-content/themes/vij/cache/');
define('BASE_VIJ', ABSPATH.'wp-content/themes/vij/');
define('IMGSERVER', 'https://img.vetandlife.ru/');
require ABSPATH.'/vendor/autoload.php';
#отключаем автообновления
//add_filter('pre_site_transient_update_core',create_function('$a', "return null;"));
//wp_clear_scheduled_hook('wp_version_check');
//remove_action( 'load-update-core.php', 'wp_update_plugins' );
//add_filter( 'pre_site_transient_update_plugins', create_function( '$a', "return null;" ) );
//wp_clear_scheduled_hook( 'wp_update_plugins' );
/* add_action( 'after_setup_theme', function(){
if ( !is_admin() )
show_admin_bar( false );
});*/
#отключаем эмодзи
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
remove_action( 'wp_print_styles', 'print_emoji_styles' );
remove_action( 'admin_print_styles', 'print_emoji_styles' );
remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );
add_filter( 'tiny_mce_plugins', 'disable_wp_emojis_in_tinymce' );
function disable_wp_emojis_in_tinymce( $plugins ) {
if ( is_array( $plugins ) ) {
return array_diff( $plugins, array( 'wpemoji' ) );
} else {
return array();
}
}
require get_template_directory().'/src/calend-block.php';
require get_template_directory().'/src/calendar.php';
require get_template_directory().'/src/perevod.php';
require get_template_directory().'/lang.php'; // функции перевода
//require get_template_directory().'/blocks/card_post_id.php';
add_post_type_support('post', 'page-attributes');
//require ABSPATH.'vendor/masterforweb/db_lite/db_lite.php';
//[_site_admin_email]
/**
function vij_send_smtp_email( PHPMailer $phpmailer ) {
$phpmailer->isSMTP();
$phpmailer->Host = 'smtp.yandex.ru';
$phpmailer->SMTPAuth = true;
$phpmailer->Port = 465;
$phpmailer->Username = 'info@vetandlife.ru';
$phpmailer->Password = 'uzpcwqbddekbwnms'; //'B9c8P6y9';
$phpmailer->SMTPSecure = 'ssl';
$phpmailer->From = 'info@vetandlife.ru';
$phpmailer->FromName = 'Ветеринария и жизнь';
}*/
function vij_send_smtp_email( PHPMailer $phpmailer ) {
$phpmailer->isSMTP();
$phpmailer->Host = 'mail.vetandlife.ru';
$phpmailer->SMTPAuth = true;
$phpmailer->Port = 465;
$phpmailer->Username = 'news@mail.vetandlife.ru';
$phpmailer->Password = 'hky~qupCAUYSn';
$phpmailer->SMTPSecure = 'ssl';
$phpmailer->From = 'news@mail.vetandlife.ru';
$phpmailer->FromName = 'Ветеринария и жизнь';
}
add_action( 'phpmailer_init', 'vij_send_smtp_email' );
db_config(DB_NAME, 'mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASSWORD);
#function wpb_change_search_url() {
# if ( is_search() && ! empty( $_GET['s'] ) ) {
# wp_redirect( home_url( "/search/" ) . urlencode( get_query_var( 's' ) ) );
# exit();
# }
#}
#add_action( 'template_redirect', 'wpb_change_search_url' );
# регистрируем меню
register_nav_menus(array(
'top' => 'Верхнее меню',
'bottom' => 'Нижнее меню',
'left' => 'Левое меню',
'mobile' => 'Мобильное меню'
));
# поддержка миниматюр
add_theme_support('post-thumbnails');
# регистрируем размеры миниатюр
//add_image_size( 'left-thumb', 95, 84, true ); # для левой колонки
//add_image_size( 'moread', 372, 216, true ); # читайте также
//add_image_size( 'subscripts', 198, 145, true ); # рассылка
#add scripts
/**
function tutsplus_burger_menu_scripts() {
wp_enqueue_script( 'burger-menu-script', get_stylesheet_directory_uri() . '/scripts/burger-menu.js', array( 'jquery' ) );
}
add_action( 'wp_enqueue_scripts', 'tutsplus_burger_menu_scripts' );
*/
/** add mobile block */
function mob_block($template){
$subclass = " mob-lite";
include get_template_directory().$template;
}
//свой шаблон для категории
add_filter('category_template', function (){
$category = get_queried_object();
$parent_id = $category->category_parent; // ID родителя
$template = array(); //массив для поиска шаблонов
$templates[] = "category-{$category->slug}.php";
$templates[] = "category-{$category->term_id}.php";
if ($parent_id > 0){
$parent = get_category($parent_id);
$templates[] = "category-{$parent->slug}.php";
$templates[] = "category-{$parent->term_id}.php";
}
$templates[] = 'category.php';
return locate_template($templates);
});
//свой шаблон для категории
add_filter( 'single_template', function ( $single_template ) {
$category = (array) get_the_category();
foreach( $category as $cat ) {
if ( file_exists(TEMPLATEPATH . "/single-{$cat->term_id}.php") ){
return TEMPLATEPATH . "/single-{$cat->term_id}.php";
}
$parent_id = $cat->parent; // шаблон гл рубрики
if ($parent_id > 0){
$parent = get_category($parent_id);
if (file_exists(TEMPLATEPATH . "/single-{$parent->term_id}.php") )
return TEMPLATEPATH . "/single-{$parent->term_id}.php";
}
}
return $single_template;
}, PHP_INT_MAX, 2 );
#search
function my_search_order( $query ) {
if (!isset( $_GET['s'] )){
return '';
}
$s = trim($_GET['s']);
if ($query->is_search) {
if (empty($query)){
$query .=" AND 0=1 ";
return $query;
}
if(strpos($s, "#") !== false) {
//$terms = explode('#', $s);
$terms = substr($s, 1);
$query->set('tax_query', [
'relation' => 'OR',
[
'taxonomy' => 'post_tag',
'field' => 'name',
'terms' => $terms
]
]);
}
// if (!isset($_GET['search_type']) OR $_GET['search_type'] == 'date'){
// $query->set( 'order', 'DESC' );
// $query->set( 'orderby', 'date' );
// }
};
return $query;
};
add_filter( 'pre_get_posts', 'my_search_order' );
function kuri_set($name = null, $value = null) {
static $vars = array();
if ($name == null)
return $vars;
if ($value == null){
if(array_key_exists($name, $vars))
return $vars[$name];
}
else
$vars[$name] = $value;
return false;
}
# время для rss
function _U2RFC822($date) {
$datatime = explode(" ",$date);
$dater = explode("-",$datatime[0]);
$timer = explode(":",$datatime[1]);
return date('r', mktime($timer[0], $timer[1], $timer[2], $dater[1], $dater[2], $dater[0]));
}
/**
* плагин перевода в латиницу
*/
add_action( 'save_post', 'lat_slug' );
function lat_slug( $post_id ){
if ($post_id < 15789)
return; // залитое старье не трогаем
// только публикованные || get_post($post_id)->post_status != 'publish'
if ( wp_is_post_revision( $post_id ))
return;
$currpost = get_post($post_id);
$name = urldecode($currpost->post_name);
if (isContainsRussianLetters($name)) { //если есть русские буковки
$title = express_slug($currpost->post_title);
$latname = vij_slug($title);
remove_action( 'save_post', 'lat_slug' ); // избегаем зацикливания
wp_update_post( array( 'ID' => $post_id, 'post_name' => $latname ) );
add_action( 'save_post', 'lat_slug' );
}
}
function vij_slug($slug) {
$replace = array(
'А' => 'A', 'а' => 'a',
'Б' => 'B', 'б' => 'b',
'В' => 'V', 'в' => 'v',
'Г' => 'G', 'г' => 'g',
'Д' => 'D', 'д' => 'd',
'Е' => 'E', 'е' => 'e',
'Ё' => 'Jo', 'ё' => 'jo',
'Ж' => 'Zh', 'ж' => 'zh',
'З' => 'Z', 'з' => 'z',
'И' => 'I', 'и' => 'i',
'Й' => 'J', 'й' => 'j',
'К' => 'K', 'к' => 'k',
'Л' => 'L', 'л' => 'l',
'М' => 'M', 'м' => 'm',
'Н' => 'N', 'н' => 'n',
'О' => 'O', 'о' => 'o',
'П' => 'P', 'п' => 'p',
'Р' => 'R', 'р' => 'r',
'С' => 'S', 'с' => 's',
'Т' => 'T', 'т' => 't',
'У' => 'U', 'у' => 'u',
'Ф' => 'F', 'ф' => 'f',
'Х' => 'H', 'х' => 'h',
'Ц' => 'C', 'ц' => 'c',
'Ч' => 'Ch', 'ч' => 'ch',
'Ш' => 'Sh', 'ш' => 'sh',
'Щ' => 'Shh', 'щ' => 'shh',
'Ъ' => '', 'ъ' => '',
'Ы' => 'Y', 'ы' => 'y',
'Ь' => '', 'ь' => '',
'Э' => 'E', 'э' => 'e',
'Ю' => 'Ju', 'ю' => 'ju',
'Я' => 'Ya', 'я' => 'ya'
);
return strtr($slug, $replace);
}
function isContainsRussianLetters($text = false) {
if ($text !== "") {
$len = strlen($text)-1;
for ($i=0;$i<=$len;$i++) {
if (($i < $len) and (((($ord = ord(substr($text,$i,1))) == 208)
and (($ord2 = ord(substr($text,($i+1),1))) == 129)
or (($ord2 >= 144) and ($ord2 <= 191)))
or ((($ord = ord(substr($text,$i,1))) == 209)
and ($ord2 == 145) or (($ord2 >= 128)
and ($ord2 <= 143))))) {
//Поиск русских букв в UTF-8
return true;
} elseif (((($ord = ord(substr($text,$i,1))) >= 192)
and (($ord <= 255)) or ($ord == 168) or ($ord == 184))) {
//Поиск русских букв в ANSI
return true;
}
}
}
return false;
}
function eventdate_str($date){
$month = array(
"01" => "января",
"02" => "февраля",
"03" => "марта",
"04" => "апреля",
"05" => "мая",
"06" => "июня",
"07" => "июля",
"08" => "августа",
"09" => "сентября",
"10" => "октября",
"11" => "ноября",
"12" => "декабря"
);
$findT = strpos($date, 'T');
if ($findT){
$currdatetime = substr($date, 0, $findT);
}
else {
$currdatetime = $date;
}
$currdate = explode("-", $currdatetime);
return $currdate[2].' '.$month[$currdate[1]].' '.$currdate[0];
}
function express_slug($value){
$result = mb_strtolower(trim($value));
$arr = [
'$' => '',
' ' => '-',
'.' => '',
'+' => '',
'!' => '',
'*' => '',
'(' => '',
')' => '',
',' => '-',
'{' => '',
'}' => '',
'|' => '-',
'^' => '',
'~' => '',
'[' => '-',
']' => '-',
'`' => '',
'<' => '',
'>' => '',
'#' => '',
'%' => '',
'"' => '',
';' => '',
'/' => '',
'?' => '',
':' => '',
'@' => '',
'&' => '',
'=' => '',
'.' => '',
'«' => '',
'»' => '',
"'"=> ''
];
$result = strtr($result, $arr);
return $result;
}
function eventdate($val){
$posT = strpos($val, 'T');
if ($posT)
return $val;
}
/**
*
*/
if (!function_exists('view')){
function view ($view, $data = array(), $layer = null){
ob_start();
if (is_array($data))
extract($data);
if ($layer !== null){
$content = view($view, $data);
require $layer;
}
else
require $view;
return trim(ob_get_clean());
}
}
function arr_to_in($items){
$in = array();
foreach ($items as $item){
$in[] = $item['post_id'];
}
return $in;
}
function str_to_in($items){
$in = '';
foreach ($items as $item){
if ($in !== '') {
$in .= ',';
}
$in .= $item['post_id'];
}
return $in;
}
add_filter( 'nav_menu_item_title', 'filter_nav_menu_item_title', 10, 4 );
function filter_nav_menu_item_title( $title, $item, $args, $depth ) {
$iconpath = TEMPLATEPATH.'/pub/menu/';
$cstart = false;
$cend = false;
$cstart = strpos($title, '<!--');
if ($cstart !== false){
$start = $cstart + 4;
$cend = strpos($title, '-->', $start + 1);
if ($cend !== false){
$svg = substr($title, $start, $cend - $start);
$svgfile = $iconpath.$svg.'.svg';
$svgcontent = file_get_contents( $svgfile);
if (file_exists( $svgfile )){
$result = str_replace("<!--$svg-->", $svgcontent , $title);
return $result;
}
}
}
return $title;
}
function lang_version(){
if (is_single()){
$current_cat = get_the_category( get_the_ID() )[0];
if ($current_cat->parent == 4782 or $current_cat->term_id == 4782 ){
return 'en';
}
}
elseif (is_category()){
$category = get_queried_object();
if ($category->parent == 4782 or $category->term_id == 4782 ){
return 'en';
}
}
elseif (is_page([17462, 17463, 17464])){
return 'en';
}
return 'ru';
}
function citata_title($percon){
$result = [];
$pos_zpt = strpos($percon, ',');
if ($pos_zpt) {
$result['percon'] = substr($percon, 0, $pos_zpt);
$result['status'] = substr($percon, $pos_zpt + 1);
}
else {
$result['percon'] = $citata;
}
return $result;
}
# helper find perevod author
function find_perevod($post_id){
$author = '';
$perevod_name = get_post_meta( $post_id, 'perevod_name', true );
if ( ! empty ( $perevod_name )){
$user_info = get_userdata($perevod_name);
if (isset($user_info->display_name)){
$author = $user_info->display_name;
}
}
if ($author !== ''){
return " / Translated by $author";
}
else {
return '';
}
}
# add concurs
/**
add_action( 'init', function () {
// Указываем метки UI для произвольного типа записи
$labels = array(
'name' => _x( 'Movies', 'Post Type General Name', 'twentythirteen' ),
'singular_name' => _x( 'Movie', 'Post Type Singular Name', 'twentythirteen' ),
'menu_name' => __( 'Movies', 'twentythirteen' ),
'parent_item_colon' => __( 'Parent Movie', 'twentythirteen' ),
'all_items' => __( 'All Movies', 'twentythirteen' ),
'view_item' => __( 'View Movie', 'twentythirteen' ),
'add_new_item' => __( 'Add New Movie', 'twentythirteen' ),
'add_new' => __( 'Add New', 'twentythirteen' ),
'edit_item' => __( 'Edit Movie', 'twentythirteen' ),
'update_item' => __( 'Update Movie', 'twentythirteen' ),
'search_items' => __( 'Search Movie', 'twentythirteen' ),
'not_found' => __( 'Not Found', 'twentythirteen' ),
'not_found_in_trash' => __( 'Not found in Trash', 'twentythirteen' ),
);
// Задаем опции для произвольного типа записи
$args = array(
'label' => __( 'Конкурсы'),
'description' => __( 'Управление конкурсами' ),
'labels' => $labels,
'supports' => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields'),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'show_in_admin_bar' => true,
'menu_position' => 5,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
// Вот здесь мы добавим таксономии в наш ПТЗ
'taxonomies' => [],
);
// Регистрируем произвольный тип записи
register_post_type( 'concurs', $args );
}, 0);
*/
add_action( 'pre_get_posts', function ($query) {
if ( ! is_admin() && $query->is_main_query() && is_category() ) {
// не админка и основной цикл страницы
// $category = get_queried_object();
// var_dump($category); exit;
if ( is_category( 'arkhiv' ) ) {
$query->set( 'posts_per_page', 8 );
}
else {
$query->set( 'posts_per_page', 25 );
}
if (is_front_page()) {
$query->set( 'posts_per_page', 24 );
}
}
if ( !is_admin() && $query->is_main_query() && is_author()) {
$query->set( 'posts_per_page', 24 );
}
});
function print_menu_shortcode($atts=[], $content = null) {
$shortcode_atts = shortcode_atts([ 'name' => '', 'class' => '' ], $atts);
$name = $shortcode_atts['name'];
$class = $shortcode_atts['class'];
return wp_nav_menu( array( 'menu' => $name, 'menu_class' => $class, 'echo' => false ) );
}
add_shortcode('menu', 'print_menu_shortcode');
function add_text_to_the_feed_end( $content ){
$content .= '
<p>
Источник: <a href="'. get_bloginfo('url') .'">'. get_bloginfo('name') .'</a>.
</p>
';
return $content;
}
add_filter( 'the_excerpt_rss', 'add_text_to_the_feed_end' );
function add_div_youtube($str){
$content = $str;
$content = str_replace(
['<iframe', '</iframe>'],
['<div class="vijdeo"><iframe', '</iframe></div>'],
$content);
// return $content;
return find_youtube($str);
}
function find_youtube($str) {
if( is_single( 11734 ) or is_single( 8136 ) ) {
return $str;
}
$result = $str;
$pos1 = strpos($str, '<iframe');
$endpos = strpos($str, '</iframe>', $pos1);
$endframe = $endpos + 9;
$iframe_len = $endframe - $pos1;
$iframe = substr($str, $pos1, $iframe_len);
$you_find = strpos($iframe, 'src="https://www.youtube.com/');
if ($you_find) {
$result = substr( $str, 0, $pos1 -1 ).'<div class="vijdeo">'.$iframe.'</div>'.substr($str, $endframe);
}
return $result;
}
add_filter('the_content', 'add_div_youtube');
add_filter( 'posts_results', 'set_query_to_draft', null, 2 );
function set_query_to_draft( $posts, &$query ) {
if ( sizeof( $posts ) != 1 )
return $posts;
$post_status_obj = get_post_status_object(get_post_status( $posts[0]));
if ( !$post_status_obj->name == 'draft' )
return $posts;
if ( !isset($_GET['key']) or $_GET['key'] != 'guest' )
return $posts;
$query->_draft_post = $posts;
add_filter( 'the_posts', 'show_draft_post', null, 2 );
}
function show_draft_post( $posts, &$query ) {
remove_filter( 'the_posts', 'show_draft_post', null, 2 );
return $query->_draft_post;
}