File: /var/www/likoholding/liko-holding.com.ua/wp-content/themes/likoholding/functions.php
<?php
/*
* Author: Todd Motto | @toddmotto
* URL: html5blank.com | @html5blank
* Custom functions, support, custom post types and more.
*/
/*------------------------------------*\
External Modules/Files
\*------------------------------------*/
// Load any external files you have here
/*------------------------------------*\
Theme Support
\*------------------------------------*/
if (!isset($content_width))
{
$content_width = 900;
}
if (function_exists('add_theme_support'))
{
// Add Menu Support
add_theme_support('menus');
// Add Thumbnail Theme Support
add_theme_support('post-thumbnails');
add_image_size('large', 700, '', true); // Large Thumbnail
add_image_size('medium', 250, '', true); // Medium Thumbnail
add_image_size('small', 120, '', true); // Small Thumbnail
add_image_size('custom-size', 700, 200, true); // Custom Thumbnail Size call using the_post_thumbnail('custom-size');
// Add Support for Custom Backgrounds - Uncomment below if you're going to use
/*add_theme_support('custom-background', array(
'default-color' => 'FFF',
'default-image' => get_template_directory_uri() . '/img/bg.jpg'
));*/
// Add Support for Custom Header - Uncomment below if you're going to use
/*add_theme_support('custom-header', array(
'default-image' => get_template_directory_uri() . '/img/headers/default.jpg',
'header-text' => false,
'default-text-color' => '000',
'width' => 1000,
'height' => 198,
'random-default' => false,
'wp-head-callback' => $wphead_cb,
'admin-head-callback' => $adminhead_cb,
'admin-preview-callback' => $adminpreview_cb
));*/
// Enables post and comment RSS feed links to head
add_theme_support('automatic-feed-links');
// Localisation Support
load_theme_textdomain('html5blank', get_template_directory() . '/languages');
}
/*------------------------------------*\
Functions
\*------------------------------------*/
// HTML5 Blank navigation
function html5blank_nav()
{
wp_nav_menu(
array(
'theme_location' => 'header-menu',
'menu' => '',
'container' => 'div',
'container_class' => 'menu-{menu slug}-container navbar navbar-expand-lg navbar-dark bg-dark',
'container_id' => '',
'menu_class' => 'menu',
'menu_id' => '',
'echo' => true,
'fallback_cb' => 'wp_page_menu',
'before' => '',
'after' => '',
'link_before' => '',
'link_after' => '',
'items_wrap' => '<ul class="navbar-nav mr-auto">%3$s</ul>',
'depth' => 0,
'walker' => ''
)
);
}
register_nav_menus(array(
'innerpage-nav' => 'Innerpage Menu',
'sales-nav' => 'Sales Menu',
'media-nav' => 'Media Menu',
));
// Load HTML5 Blank scripts (header.php)
function html5blank_header_scripts()
{
if ($GLOBALS['pagenow'] != 'wp-login.php' && !is_admin()) {
wp_register_script('conditionizr', get_template_directory_uri() . '/js/lib/conditionizr-4.3.0.min.js', array(), '4.3.0'); // Conditionizr
wp_enqueue_script('conditionizr'); // Enqueue it!
wp_register_script('modernizr', get_template_directory_uri() . '/js/lib/modernizr-2.7.1.min.js', array(), '2.7.1'); // Modernizr
wp_enqueue_script('modernizr'); // Enqueue it!
wp_register_script('html5blankscripts', get_template_directory_uri() . '/js/scripts.js', array('jquery'), '1.0.0'); // Custom scripts
wp_enqueue_script('html5blankscripts'); // Enqueue it!
}
}
// Load HTML5 Blank conditional scripts
function html5blank_conditional_scripts()
{
if (is_page('pagenamehere')) {
wp_register_script('scriptname', get_template_directory_uri() . '/js/scriptname.js', array('jquery'), '1.0.0'); // Conditional script(s)
wp_enqueue_script('scriptname'); // Enqueue it!
}
}
// Load HTML5 Blank stylesbootstrap.js
function html5blank_styles()
{
wp_register_style('normalize', get_template_directory_uri() . '/normalize.css', array(), '1.0', 'all');
wp_enqueue_style('normalize'); // Enqueue it!
wp_register_style('html5blank', get_template_directory_uri() . '/style.css', array(), '1.0', 'all');
wp_enqueue_style('html5blank'); // Enqueue it!
}
// Register HTML5 Blank Navigation
function register_html5_menu()
{
register_nav_menus(array( // Using array to specify more menus if needed
'header-menu' => __('Header Menu', 'html5blank'), // Main Navigation
'sidebar-menu' => __('Sidebar Menu', 'html5blank'), // Sidebar Navigation
'extra-menu' => __('Extra Menu', 'html5blank') // Extra Navigation if needed (duplicate as many as you need!)
));
}
// Remove the <div> surrounding the dynamic navigation to cleanup markup
function my_wp_nav_menu_args($args = '')
{
$args['container'] = false;
return $args;
}
// Remove Injected classes, ID's and Page ID's from Navigation <li> items
function my_css_attributes_filter($var)
{
return is_array($var) ? array() : '';
}
// Remove invalid rel attribute values in the categorylist
function remove_category_rel_from_category_list($thelist)
{
return str_replace('rel="category tag"', 'rel="tag"', $thelist);
}
// Add page slug to body class, love this - Credit: Starkers Wordpress Theme
function add_slug_to_body_class($classes)
{
global $post;
if (is_home()) {
$key = array_search('blog', $classes);
if ($key > -1) {
unset($classes[$key]);
}
} elseif (is_page()) {
$classes[] = sanitize_html_class($post->post_name);
} elseif (is_singular()) {
$classes[] = sanitize_html_class($post->post_name);
}
return $classes;
}
// If Dynamic Sidebar Exists
if (function_exists('register_sidebar'))
{
// Define Sidebar Widget Area 1
register_sidebar(array(
'name' => __('Widget Area 1', 'html5blank'),
'description' => __('Description for this widget-area...', 'html5blank'),
'id' => 'widget-area-1',
'before_widget' => '<div id="%1$s" class="%2$s">',
'after_widget' => '</div>',
'before_title' => '<h3>',
'after_title' => '</h3>'
));
// Define Sidebar Widget Area 2
register_sidebar(array(
'name' => __('Widget Area 2', 'html5blank'),
'description' => __('Description for this widget-area...', 'html5blank'),
'id' => 'widget-area-2',
'before_widget' => '<div id="%1$s" class="%2$s">',
'after_widget' => '</div>',
'before_title' => '<h3>',
'after_title' => '</h3>'
));
}
// Remove wp_head() injected Recent Comment styles
function my_remove_recent_comments_style()
{
global $wp_widget_factory;
remove_action('wp_head', array(
$wp_widget_factory->widgets['WP_Widget_Recent_Comments'],
'recent_comments_style'
));
}
// Pagination for paged posts, Page 1, Page 2, Page 3, with Next and Previous Links, No plugin
function html5wp_pagination()
{
global $wp_query;
$big = 999999999;
echo paginate_links(array(
'base' => str_replace($big, '%#%', get_pagenum_link($big)),
'format' => '?paged=%#%',
'current' => max(1, get_query_var('paged')),
'total' => $wp_query->max_num_pages
));
}
// Custom Excerpts
function html5wp_index($length) // Create 20 Word Callback for Index page Excerpts, call using html5wp_excerpt('html5wp_index');
{
return 20;
}
// Create 40 Word Callback for Custom Post Excerpts, call using html5wp_excerpt('html5wp_custom_post');
function html5wp_custom_post($length)
{
return 40;
}
// Create the Custom Excerpts callback
function html5wp_excerpt($length_callback = '', $more_callback = '')
{
global $post;
if (function_exists($length_callback)) {
add_filter('excerpt_length', $length_callback);
}
if (function_exists($more_callback)) {
add_filter('excerpt_more', $more_callback);
}
$output = get_the_excerpt();
$output = apply_filters('wptexturize', $output);
$output = apply_filters('convert_chars', $output);
$output = '<p>' . $output . '</p>';
echo $output;
}
// Custom View Article link to Post
function html5_blank_view_article($more)
{
global $post;
return '... <a class="view-article" href="' . get_permalink($post->ID) . '">' . __('View Article', 'html5blank') . '</a>';
}
// Remove Admin bar
function remove_admin_bar()
{
return false;
}
// Remove 'text/css' from our enqueued stylesheet
function html5_style_remove($tag)
{
return preg_replace('~\s+type=["\'][^"\']++["\']~', '', $tag);
}
// Remove thumbnail width and height dimensions that prevent fluid images in the_thumbnail
function remove_thumbnail_dimensions( $html )
{
$html = preg_replace('/(width|height)=\"\d*\"\s/', "", $html);
return $html;
}
// Custom Gravatar in Settings > Discussion
function html5blankgravatar ($avatar_defaults)
{
$myavatar = get_template_directory_uri() . '/img/gravatar.jpg';
$avatar_defaults[$myavatar] = "Custom Gravatar";
return $avatar_defaults;
}
// Threaded Comments
function enable_threaded_comments()
{
if (!is_admin()) {
if (is_singular() AND comments_open() AND (get_option('thread_comments') == 1)) {
wp_enqueue_script('comment-reply');
}
}
}
// Custom Comments Callback
function html5blankcomments($comment, $args, $depth)
{
$GLOBALS['comment'] = $comment;
extract($args, EXTR_SKIP);
if ( 'div' == $args['style'] ) {
$tag = 'div';
$add_below = 'comment';
} else {
$tag = 'li';
$add_below = 'div-comment';
}
?>
<!-- heads up: starting < for the html tag (li or div) in the next line: -->
<<?php echo $tag ?> <?php comment_class(empty( $args['has_children'] ) ? '' : 'parent') ?> id="comment-<?php comment_ID() ?>">
<?php if ( 'div' != $args['style'] ) : ?>
<div id="div-comment-<?php comment_ID() ?>" class="comment-body">
<?php endif; ?>
<div class="comment-author vcard">
<?php if ($args['avatar_size'] != 0) echo get_avatar( $comment, $args['180'] ); ?>
<?php printf(__('<cite class="fn">%s</cite> <span class="says">says:</span>'), get_comment_author_link()) ?>
</div>
<?php if ($comment->comment_approved == '0') : ?>
<em class="comment-awaiting-moderation"><?php _e('Your comment is awaiting moderation.') ?></em>
<br />
<?php endif; ?>
<div class="comment-meta commentmetadata"><a href="<?php echo htmlspecialchars( get_comment_link( $comment->comment_ID ) ) ?>">
<?php
printf( __('%1$s at %2$s'), get_comment_date(), get_comment_time()) ?></a><?php edit_comment_link(__('(Edit)'),' ','' );
?>
</div>
<?php comment_text() ?>
<div class="reply">
<?php comment_reply_link(array_merge( $args, array('add_below' => $add_below, 'depth' => $depth, 'max_depth' => $args['max_depth']))) ?>
</div>
<?php if ( 'div' != $args['style'] ) : ?>
</div>
<?php endif; ?>
<?php }
/*------------------------------------*\
Actions + Filters + ShortCodes
\*------------------------------------*/
// Add Actions
add_action('init', 'html5blank_header_scripts'); // Add Custom Scripts to wp_head
add_action('wp_print_scripts', 'html5blank_conditional_scripts'); // Add Conditional Page Scripts
add_action('get_header', 'enable_threaded_comments'); // Enable Threaded Comments
add_action('wp_enqueue_scripts', 'html5blank_styles'); // Add Theme Stylesheet
add_action('init', 'register_html5_menu'); // Add HTML5 Blank Menu
//add_action('init', 'create_post_type_html5'); // Add our HTML5 Blank Custom Post Type
add_action('widgets_init', 'my_remove_recent_comments_style'); // Remove inline Recent Comment Styles from wp_head()
add_action('init', 'html5wp_pagination'); // Add our HTML5 Pagination
// Remove Actions
remove_action('wp_head', 'feed_links_extra', 3); // Display the links to the extra feeds such as category feeds
remove_action('wp_head', 'feed_links', 2); // Display the links to the general feeds: Post and Comment Feed
remove_action('wp_head', 'rsd_link'); // Display the link to the Really Simple Discovery service endpoint, EditURI link
remove_action('wp_head', 'wlwmanifest_link'); // Display the link to the Windows Live Writer manifest file.
remove_action('wp_head', 'index_rel_link'); // Index link
remove_action('wp_head', 'parent_post_rel_link', 10, 0); // Prev link
remove_action('wp_head', 'start_post_rel_link', 10, 0); // Start link
remove_action('wp_head', 'adjacent_posts_rel_link', 10, 0); // Display relational links for the posts adjacent to the current post.
remove_action('wp_head', 'wp_generator'); // Display the XHTML generator that is generated on the wp_head hook, WP version
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
remove_action('wp_head', 'rel_canonical');
remove_action('wp_head', 'wp_shortlink_wp_head', 10, 0);
// Add Filters
add_filter('avatar_defaults', 'html5blankgravatar'); // Custom Gravatar in Settings > Discussion
add_filter('body_class', 'add_slug_to_body_class'); // Add slug to body class (Starkers build)
add_filter('widget_text', 'do_shortcode'); // Allow shortcodes in Dynamic Sidebar
add_filter('widget_text', 'shortcode_unautop'); // Remove <p> tags in Dynamic Sidebars (better!)
add_filter('wp_nav_menu_args', 'my_wp_nav_menu_args'); // Remove surrounding <div> from WP Navigation
// add_filter('nav_menu_css_class', 'my_css_attributes_filter', 100, 1); // Remove Navigation <li> injected classes (Commented out by default)
// add_filter('nav_menu_item_id', 'my_css_attributes_filter', 100, 1); // Remove Navigation <li> injected ID (Commented out by default)
// add_filter('page_css_class', 'my_css_attributes_filter', 100, 1); // Remove Navigation <li> Page ID's (Commented out by default)
add_filter('the_category', 'remove_category_rel_from_category_list'); // Remove invalid rel attribute
add_filter('the_excerpt', 'shortcode_unautop'); // Remove auto <p> tags in Excerpt (Manual Excerpts only)
add_filter('the_excerpt', 'do_shortcode'); // Allows Shortcodes to be executed in Excerpt (Manual Excerpts only)
add_filter('excerpt_more', 'html5_blank_view_article'); // Add 'View Article' button instead of [...] for Excerpts
add_filter('show_admin_bar', 'remove_admin_bar'); // Remove Admin bar
add_filter('style_loader_tag', 'html5_style_remove'); // Remove 'text/css' from enqueued stylesheet
add_filter('post_thumbnail_html', 'remove_thumbnail_dimensions', 10); // Remove width and height dynamic attributes to thumbnails
add_filter('image_send_to_editor', 'remove_thumbnail_dimensions', 10); // Remove width and height dynamic attributes to post images
// Remove Filters
remove_filter('the_excerpt', 'wpautop'); // Remove <p> tags from Excerpt altogether
// Shortcodes
add_shortcode('html5_shortcode_demo', 'html5_shortcode_demo'); // You can place [html5_shortcode_demo] in Pages, Posts now.
add_shortcode('html5_shortcode_demo_2', 'html5_shortcode_demo_2'); // Place [html5_shortcode_demo_2] in Pages, Posts now.
// Shortcodes above would be nested like this -
// [html5_shortcode_demo] [html5_shortcode_demo_2] Here's the page title! [/html5_shortcode_demo_2] [/html5_shortcode_demo]
/*------------------------------------*\
Custom Post Types
\*------------------------------------*/
// Create 1 Custom Post type for a Demo, called HTML5-Blank
function create_post_type_html5()
{
register_taxonomy_for_object_type('category', 'html5-blank'); // Register Taxonomies for Category
register_taxonomy_for_object_type('post_tag', 'html5-blank');
register_post_type('html5-blank', // Register Custom Post Type
array(
'labels' => array(
'name' => __('html5blank', 'html5blank'), // Rename these to suit
'singular_name' => __('HTML5 Blank Custom Post', 'html5blank'),
'add_new' => __('Add New', 'html5blank'),
'add_new_item' => __('Add New HTML5 Blank Custom Post', 'html5blank'),
'edit' => __('Edit', 'html5blank'),
'edit_item' => __('Edit HTML5 Blank Custom Post', 'html5blank'),
'new_item' => __('New HTML5 Blank Custom Post', 'html5blank'),
'view' => __('View HTML5 Blank Custom Post', 'html5blank'),
'view_item' => __('View HTML5 Blank Custom Post', 'html5blank'),
'search_items' => __('Search HTML5 Blank Custom Post', 'html5blank'),
'not_found' => __('No HTML5 Blank Custom Posts found', 'html5blank'),
'not_found_in_trash' => __('No HTML5 Blank Custom Posts found in Trash', 'html5blank')
),
'public' => true,
'hierarchical' => true, // Allows your posts to behave like Hierarchy Pages
'has_archive' => true,
'supports' => array(
'title',
'editor',
'excerpt',
'thumbnail'
), // Go to Dashboard Custom HTML5 Blank post for supports
'can_export' => true, // Allows export in Tools > Export
'taxonomies' => array(
'post_tag',
'category'
) // Add Category and Post Tags support
));
}
/*------------------------------------*\
ShortCode Functions
\*------------------------------------*/
// Shortcode Demo with Nested Capability
function html5_shortcode_demo($atts, $content = null)
{
return '<div class="shortcode-demo">' . do_shortcode($content) . '</div>'; // do_shortcode allows for nested Shortcodes
}
// Shortcode Demo with simple <h2> tag
function html5_shortcode_demo_2($atts, $content = null) // Demo Heading H2 shortcode, allows for nesting within above element. Fully expandable.
{
return '<h2>' . $content . '</h2>';
}
function custom_adminstyles() {
echo '<style type="text/css">
#wp-postimgpop-editor-tools .wp-editor-tabs,
#wp-postimgpop-editor-container .mce-toolbar-grp,
#wp-postsliderright-editor-tools .wp-editor-tabs,
#wp-postsliderright-editor-container .mce-toolbar-grp {
visibility: hidden;
height: 0px;
}
#postsliderrighttext_ifr {
height: 200px!important;
}
</style>';
}
add_action('admin_head', 'custom_adminstyles');
function chromefix_inline_css() { wp_add_inline_style( 'wp-admin', '#adminmenu { transform: translateZ(0); }' ); }
add_action('admin_enqueue_scripts', 'chromefix_inline_css');
add_action( 'init', 'true_register_news' );
function true_register_news() {
$labels_news = array(
'name' => 'Новости Прес-Центр',
'singular_name' => 'Новости Прес-Центр',
'add_new' => 'Добавить Новость',
'add_new_item' => 'Добавить новою Новость', // заголовок тега <title>
'edit_item' => 'Редактировать Новость',
'new_item' => 'Новая Новость',
'all_items' => 'Все Новости',
'view_item' => 'Просмотр Новости на сайте',
'search_items' => 'Искать Новость',
'not_found' => 'Новостей не найдено.',
'not_found_in_trash' => 'В корзине нет Новостей',
'menu_name' => 'Новости Прес-Центр' // ссылка в меню в админке
);
$argsnews = array(
'labels' => $labels_news,
'public' => true, // благодаря этому некоторые параметры можно пропустить
'menu_icon' => 'dashicons-images-alt', // иконка корзины
'menu_position' => 5,
'has_archive' => 'newspress',
'supports' => array( 'title', 'editor', 'thumbnail', 'comments'),
'taxonomies' => array('post_tag')
);
register_post_type('newspress',$argsnews);
}
function news_taxonomy() {
register_taxonomy(
'news_categories', //The name of the taxonomy. Name should be in slug form (must not contain capital letters or spaces).
'newspress', //post type name
array(
'hierarchical' => true,
'label' => 'Группы новостей', //Display name
'query_var' => true,
'rewrite' => array(
'slug' => 'newspress', // This controls the base slug that will display before each term
'with_front' => false // Don't display the category base before
)
)
);
}
add_action( 'init', 'news_taxonomy');
/**
* Хлебные крошки для WordPress (breadcrumbs)
*
* @param string [$sep = ''] Разделитель. По умолчанию ' » '
* @param array [$l10n = array()] Для локализации. См. переменную $default_l10n.
* @param array [$args = array()] Опции. См. переменную $def_args
* @return string Выводит на экран HTML код
*
* version 3.3.2
*/
function kama_breadcrumbs( $sep = ' » ', $l10n = array(), $args = array() ){
$kb = new Kama_Breadcrumbs;
$lang = get_locale();
if ($lang =='uk') {
$l10n = array(
'home' => 'Головна',
'paged' => 'Сторінка %d',
'_404' => 'Помилка 404',
'search' => 'Результати пошуку по запиту - <b>%s</b>',
'author' => 'Архів автора: <b>%s</b>',
'year' => 'Архів за <b>%d</b> год',
'month' => 'Архів за: <b>%s</b>',
'day' => '',
'attachment' => 'Медіа: %s',
'tag' => 'Запис по мітці: <b>%s</b>',
'tax_tag' => '%1$s із "%2$s" по тегу: <b>%3$s</b>',
// tax_tag выведет: 'тип_записи из "название_таксы" по тегу: имя_термина'.
// Если нужны отдельные холдеры, например только имя термина, пишем так: 'записи по тегу: %3$s'
);
}elseif($lang == 'en_US'){
$l10n = array(
'home' => 'Home',
'paged' => 'Page %d',
'_404' => 'Error 404',
'search' => 'Результати пошуку по запиту - <b>%s</b>',
'author' => 'Author archive: <b>%s</b>',
'year' => 'Archive for <b>%d</b> год',
'month' => 'Archive for: <b>%s</b>',
'day' => '',
'attachment' => 'Media: %s',
'tag' => 'Record by label: <b>%s</b>',
'tax_tag' => '%1$s from "%2$s" by tag: <b>%3$s</b>',
// tax_tag выведет: 'тип_записи из "название_таксы" по тегу: имя_термина'.
// Если нужны отдельные холдеры, например только имя термина, пишем так: 'записи по тегу: %3$s'
);
}
echo $kb->get_crumbs( $sep, $l10n, $args );
}
class Kama_Breadcrumbs {
public $arg;
// Локализация
static $l10n = array(
'home' => 'Головна',
'paged' => 'Сторінка %d',
'_404' => 'Помилка 404',
'search' => 'Результати пошуку по запиту - <b>%s</b>',
'author' => 'Архів автора: <b>%s</b>',
'year' => 'Архів за <b>%d</b> год',
'month' => 'Архів за: <b>%s</b>',
'day' => '',
'attachment' => 'Медіа: %s',
'tag' => 'Запис по мітціе: <b>%s</b>',
'tax_tag' => '%1$s із "%2$s" по тегу: <b>%3$s</b>',
// tax_tag выведет: 'тип_записи из "название_таксы" по тегу: имя_термина'.
// Если нужны отдельные холдеры, например только имя термина, пишем так: 'записи по тегу: %3$s'
);
// Параметры по умолчанию
static $args = array(
'on_front_page' => true, // выводить крошки на главной странице
'show_post_title' => true, // показывать ли название записи в конце (последний элемент). Для записей, страниц, вложений
'show_term_title' => true, // показывать ли название элемента таксономии в конце (последний элемент). Для меток, рубрик и других такс
'title_patt' => '<span class="kb_title">%s</span>', // шаблон для последнего заголовка. Если включено: show_post_title или show_term_title
'last_sep' => true, // показывать последний разделитель, когда заголовок в конце не отображается
'markup' => 'schema.org', // 'markup' - микроразметка. Может быть: 'rdf.data-vocabulary.org', 'schema.org', '' - без микроразметки
// или можно указать свой массив разметки:
// array( 'wrappatt'=>'<div class="kama_breadcrumbs">%s</div>', 'linkpatt'=>'<a href="%s">%s</a>', 'sep_after'=>'', )
'priority_tax' => array('category'), // приоритетные таксономии, нужно когда запись в нескольких таксах
'priority_terms' => array(), // 'priority_terms' - приоритетные элементы таксономий, когда запись находится в нескольких элементах одной таксы одновременно.
// Например: array( 'category'=>array(45,'term_name'), 'tax_name'=>array(1,2,'name') )
// 'category' - такса для которой указываются приор. элементы: 45 - ID термина и 'term_name' - ярлык.
// порядок 45 и 'term_name' имеет значение: чем раньше тем важнее. Все указанные термины важнее неуказанных...
'nofollow' => false, // добавлять rel=nofollow к ссылкам?
// служебные
'sep' => '',
'linkpatt' => '',
'pg_end' => '',
);
function get_crumbs( $sep, $l10n, $args ){
global $post, $wp_query, $wp_post_types;
self::$args['sep'] = $sep;
// Фильтрует дефолты и сливает
$loc = (object) array_merge( apply_filters('kama_breadcrumbs_default_loc', self::$l10n ), $l10n );
$arg = (object) array_merge( apply_filters('kama_breadcrumbs_default_args', self::$args ), $args );
$arg->sep = '<span class="kb_sep">'. $arg->sep .'</span>'; // дополним
// упростим
$sep = & $arg->sep;
$this->arg = & $arg;
// микроразметка ---
if(1){
$mark = & $arg->markup;
// Разметка по умолчанию
if( ! $mark ) $mark = array(
'wrappatt' => '<div class="kama_breadcrumbs">%s</div>',
'linkpatt' => '<a href="%s">%s</a>',
'sep_after' => '',
);
// rdf
elseif( $mark === 'rdf.data-vocabulary.org' ) $mark = array(
'wrappatt' => '<div class="kama_breadcrumbs" prefix="v: http://rdf.data-vocabulary.org/#">%s</div>',
'linkpatt' => '<span typeof="v:Breadcrumb"><a href="%s" rel="v:url" property="v:title">%s</a>',
'sep_after' => '</span>', // закрываем span после разделителя!
);
// schema.org
elseif( $mark === 'schema.org' ) $mark = array(
'wrappatt' => '<div class="kama_breadcrumbs" itemscope itemtype="http://schema.org/BreadcrumbList">%s</div>',
'linkpatt' => '<span itemprop="itemListElement" itemscope itemtype="http://schema.org/ListItem"><a href="%s" itemprop="item"><span itemprop="name">%s</span></a></span>',
'sep_after' => '',
);
elseif( ! is_array($mark) )
die( __CLASS__ .': "markup" parameter must be array...');
$wrappatt = $mark['wrappatt'];
$arg->linkpatt = $arg->nofollow ? str_replace('<a ','<a rel="nofollow"', $mark['linkpatt']) : $mark['linkpatt'];
$arg->sep .= $mark['sep_after']."\n";
}
$linkpatt = $arg->linkpatt; // упростим
$q_obj = get_queried_object();
// может это архив пустой таксы?
$ptype = null;
if( empty($post) ){
if( isset($q_obj->taxonomy) )
$ptype = & $wp_post_types[ get_taxonomy($q_obj->taxonomy)->object_type[0] ];
}
else $ptype = & $wp_post_types[ $post->post_type ];
// paged
$arg->pg_end = '';
if( ($paged_num = get_query_var('paged')) || ($paged_num = get_query_var('page')) )
$arg->pg_end = $sep . sprintf( $loc->paged, (int) $paged_num );
$pg_end = $arg->pg_end; // упростим
$out = '';
if( is_front_page() ){
return $arg->on_front_page ? sprintf( $wrappatt, ( $paged_num ? sprintf($linkpatt, get_home_url(), $loc->home) . $pg_end : $loc->home ) ) : '';
}
// страница записей, когда для главной установлена отдельная страница.
elseif( is_home() ) {
$out = $paged_num ? ( sprintf( $linkpatt, get_permalink($q_obj), esc_html($q_obj->post_title) ) . $pg_end ) : esc_html($q_obj->post_title);
}
elseif( is_404() ){
$out = $loc->_404;
}
elseif( is_search() ){
$out = sprintf( $loc->search, esc_html( $GLOBALS['s'] ) );
}
elseif( is_author() ){
$tit = sprintf( $loc->author, esc_html($q_obj->display_name) );
$out = ( $paged_num ? sprintf( $linkpatt, get_author_posts_url( $q_obj->ID, $q_obj->user_nicename ) . $pg_end, $tit ) : $tit );
}
elseif( is_year() || is_month() || is_day() ){
$y_url = get_year_link( $year = get_the_time('Y') );
if( is_year() ){
$tit = sprintf( $loc->year, $year );
$out = ( $paged_num ? sprintf($linkpatt, $y_url, $tit) . $pg_end : $tit );
}
// month day
else {
$y_link = sprintf( $linkpatt, $y_url, $year);
$m_url = get_month_link( $year, get_the_time('m') );
if( is_month() ){
$tit = sprintf( $loc->month, get_the_time('F') );
$out = $y_link . $sep . ( $paged_num ? sprintf( $linkpatt, $m_url, $tit ) . $pg_end : $tit );
}
elseif( is_day() ){
$m_link = sprintf( $linkpatt, $m_url, get_the_time('F'));
$out = $y_link . $sep . $m_link . $sep . get_the_time('l');
}
}
}
// Древовидные записи
elseif( is_singular() && $ptype->hierarchical ){
$out = $this->_add_title( $this->_page_crumbs($post), $post );
}
// Таксы, плоские записи и вложения
else {
$term = $q_obj; // таксономии
// определяем термин для записей (включая вложения attachments)
if( is_singular() ){
// изменим $post, чтобы определить термин родителя вложения
if( is_attachment() && $post->post_parent ){
$save_post = $post; // сохраним
$post = get_post($post->post_parent);
}
// учитывает если вложения прикрепляются к таксам древовидным - все бывает :)
$taxonomies = get_object_taxonomies( $post->post_type );
// оставим только древовидные и публичные, мало ли...
$taxonomies = array_intersect( $taxonomies, get_taxonomies( array('hierarchical' => true, 'public' => true) ) );
if( $taxonomies ){
// сортируем по приоритету
if( ! empty($arg->priority_tax) ){
usort( $taxonomies, function($a,$b)use($arg){
$a_index = array_search($a, $arg->priority_tax);
if( $a_index === false ) $a_index = 9999999;
$b_index = array_search($b, $arg->priority_tax);
if( $b_index === false ) $b_index = 9999999;
return ( $b_index === $a_index ) ? 0 : ( $b_index < $a_index ? 1 : -1 ); // меньше индекс - выше
} );
}
// пробуем получить термины, в порядке приоритета такс
foreach( $taxonomies as $taxname ){
if( $terms = get_the_terms( $post->ID, $taxname ) ){
// проверим приоритетные термины для таксы
$prior_terms = & $arg->priority_terms[ $taxname ];
if( $prior_terms && count($terms) > 2 ){
foreach( (array) $prior_terms as $term_id ){
$filter_field = is_numeric($term_id) ? 'term_id' : 'slug';
$_terms = wp_list_filter( $terms, array($filter_field=>$term_id) );
if( $_terms ){
$term = array_shift( $_terms );
break;
}
}
}
else
$term = array_shift( $terms );
break;
}
}
}
if( isset($save_post) ) $post = $save_post; // вернем обратно (для вложений)
}
// вывод
// все виды записей с терминами или термины
if( $term && isset($term->term_id) ){
$term = apply_filters('kama_breadcrumbs_term', $term );
// attachment
if( is_attachment() ){
if( ! $post->post_parent )
$out = sprintf( $loc->attachment, esc_html($post->post_title) );
else {
if( ! $out = apply_filters('attachment_tax_crumbs', '', $term, $this ) ){
$_crumbs = $this->_tax_crumbs( $term, 'self' );
$parent_tit = sprintf( $linkpatt, get_permalink($post->post_parent), get_the_title($post->post_parent) );
$_out = implode( $sep, array($_crumbs, $parent_tit) );
$out = $this->_add_title( $_out, $post );
}
}
}
// single
elseif( is_single() ){
if( ! $out = apply_filters('post_tax_crumbs', '', $term, $this ) ){
$_crumbs = $this->_tax_crumbs( $term, 'self' );
$out = $this->_add_title( $_crumbs, $post );
}
}
// не древовидная такса (метки)
elseif( ! is_taxonomy_hierarchical($term->taxonomy) ){
// метка
if( is_tag() )
$out = $this->_add_title('', $term, sprintf( $loc->tag, esc_html($term->name) ) );
// такса
elseif( is_tax() ){
$post_label = $ptype->labels->name;
$tax_label = $GLOBALS['wp_taxonomies'][ $term->taxonomy ]->labels->name;
$out = $this->_add_title('', $term, sprintf( $loc->tax_tag, $post_label, $tax_label, esc_html($term->name) ) );
}
}
// древовидная такса (рибрики)
else {
if( ! $out = apply_filters('term_tax_crumbs', '', $term, $this ) ){
$_crumbs = $this->_tax_crumbs( $term, 'parent' );
$out = $this->_add_title( $_crumbs, $term, esc_html($term->name) );
}
}
}
// влоежния от записи без терминов
elseif( is_attachment() ){
$parent = get_post($post->post_parent);
$parent_link = sprintf( $linkpatt, get_permalink($parent), esc_html($parent->post_title) );
$_out = $parent_link;
// вложение от записи древовидного типа записи
if( is_post_type_hierarchical($parent->post_type) ){
$parent_crumbs = $this->_page_crumbs($parent);
$_out = implode( $sep, array( $parent_crumbs, $parent_link ) );
}
$out = $this->_add_title( $_out, $post );
}
// записи без терминов
elseif( is_singular() ){
$out = $this->_add_title( '', $post );
}
}
// замена ссылки на архивную страницу для типа записи
$home_after = apply_filters('kama_breadcrumbs_home_after', '', $linkpatt, $sep, $ptype );
if( '' === $home_after ){
// Ссылка на архивную страницу типа записи для: отдельных страниц этого типа; архивов этого типа; таксономий связанных с этим типом.
if( $ptype && $ptype->has_archive && ! in_array( $ptype->name, array('post','page','attachment') )
&& ( is_post_type_archive() || is_singular() || (is_tax() && in_array($term->taxonomy, $ptype->taxonomies)) )
){
$pt_title = $ptype->labels->name;
// первая страница архива типа записи
if( is_post_type_archive() && ! $paged_num )
$home_after = sprintf( $this->arg->title_patt, $pt_title );
// singular, paged post_type_archive, tax
else{
$home_after = sprintf( $linkpatt, get_post_type_archive_link($ptype->name), $pt_title );
$home_after .= ( ($paged_num && ! is_tax()) ? $pg_end : $sep ); // пагинация
}
}
}
$before_out = sprintf( $linkpatt, home_url(), $loc->home ) . ( $home_after ? $sep.$home_after : ($out ? $sep : '') );
$out = apply_filters('kama_breadcrumbs_pre_out', $out, $sep, $loc, $arg );
$out = sprintf( $wrappatt, $before_out . $out );
return apply_filters('kama_breadcrumbs', $out, $sep, $loc, $arg );
}
function _page_crumbs( $post ){
$parent = $post->post_parent;
$crumbs = array();
while( $parent ){
$page = get_post( $parent );
$crumbs[] = sprintf( $this->arg->linkpatt, get_permalink($page), esc_html($page->post_title) );
$parent = $page->post_parent;
}
return implode( $this->arg->sep, array_reverse($crumbs) );
}
function _tax_crumbs( $term, $start_from = 'self' ){
$termlinks = array();
$term_id = ($start_from === 'parent') ? $term->parent : $term->term_id;
while( $term_id ){
$term = get_term( $term_id, $term->taxonomy );
$termlinks[] = sprintf( $this->arg->linkpatt, get_term_link($term), esc_html($term->name) );
$term_id = $term->parent;
}
if( $termlinks )
return implode( $this->arg->sep, array_reverse($termlinks) ) /*. $this->arg->sep*/;
return '';
}
// добалвяет заголовок к переданному тексту, с учетом всех опций. Добавляет разделитель в начало, если надо.
function _add_title( $add_to, $obj, $term_title = '' ){
$arg = & $this->arg; // упростим...
$title = $term_title ? $term_title : esc_html($obj->post_title); // $term_title чиститься отдельно, теги моугт быть...
$show_title = $term_title ? $arg->show_term_title : $arg->show_post_title;
// пагинация
if( $arg->pg_end ){
$link = $term_title ? get_term_link($obj) : get_permalink($obj);
$add_to .= ($add_to ? $arg->sep : '') . sprintf( $arg->linkpatt, $link, $title ) . $arg->pg_end;
}
// дополняем - ставим sep
elseif( $add_to ){
if( $show_title )
$add_to .= $arg->sep . sprintf( $arg->title_patt, $title );
elseif( $arg->last_sep )
$add_to .= $arg->sep;
}
// sep будет потом...
elseif( $show_title )
$add_to = sprintf( $arg->title_patt, $title );
return $add_to;
}
}
add_action('init', function() {
pll_register_string('likoholding', 'Detail');
pll_register_string('likoholding', 'Buy property:');
pll_register_string('likoholding', 'To order a call');
pll_register_string('likoholding', 'UK Likozhytloservis');
pll_register_string('likoholding', 'Promotions');
pll_register_string('likoholding', 'Gallery');
pll_register_string('likoholding', 'Back');
pll_register_string('likoholding', 'Online');
pll_register_string('likoholding', 'broadcast');
pll_register_string('likoholding', 'News');
pll_register_string('likoholding', 'History of construction');
pll_register_string('likoholding', 'Address');
pll_register_string('likoholding', 'Construction progress:');
pll_register_string('likoholding', 'Terms of purchase:');
pll_register_string('likoholding', 'There are currently no vacancies available
');
pll_register_string('likoholding', 'Terms of purchase:');
pll_register_string('likoholding', 'Contact');
pll_register_string('likoholding', 'Map');
pll_register_string('likoholding', 'Headquarters Sales');
pll_register_string('likoholding', 'Search');
pll_register_string('likoholding', 'Available apartments');
pll_register_string('likoholding', 'Search Results for');
});