<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Add preconnect for Google Fonts.
 *
 *
 * @param array  $urls           URLs to print for resource hints.
 * @param string $relation_type  The relation type the URLs are printed.
 * @return array $urls           URLs to print for resource hints.
 */
function custom_resource_hints( $urls, $relation_type ) {
	global $ime_theme;
	if ( wp_style_is( ''.$ime_theme.'-fonts', 'queue' ) && 'preconnect' === $relation_type ) {
		$urls[] = array(
			'href' => 'https://fonts.gstatic.com',
			'crossorigin',
		);
	}

	return $urls;
}

// ucfirst za šumnike
function custom_mb_ucfirst($str, $encoding = 'UTF-8') {
    $firstChar = mb_substr($str, 0, 1, $encoding);
	$uppercase = false;
	$uppercase = strpos($str, "'");
	if($uppercase){
		// get uppercase text
		$uppercaseText = substr($str, $uppercase, strrpos($str, "'"));
		$cuttedStr = substr($str, 0, $uppercase);
	    $str = mb_strtoupper($firstChar, $encoding) . mb_substr(mb_strtolower($cuttedStr, $encoding), 1, mb_strlen($cuttedStr), $encoding) . trim(str_replace("'", "", $uppercaseText));
	}
	else {
	    $str = mb_strtoupper($firstChar, $encoding) . mb_substr(mb_strtolower($str, $encoding), 1, mb_strlen($str), $encoding);
	}
    return $str;
}

function new_nav_menu_items($items) {
	$items = preg_replace_callback("/<a.*?>(.*?)<\/[\s]*a>/", "custom_mb_ucfirst", $items);
	return $items;
}

// Adds custom classes to the array of body classes
function custom_body_classes( $classes ) {
	// add post type and post slug to body 	
	global $post;
	
	// Add awesome browser classes to body tag
	global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone;

	if($is_lynx) $classes[] = 'lynx';
	elseif($is_gecko) $classes[] = 'gecko';
	elseif($is_opera) $classes[] = 'opera';
	elseif($is_NS4) $classes[] = 'ns4';
	elseif($is_safari) $classes[] = 'safari';
	elseif($is_chrome) $classes[] = 'chrome';
	elseif($is_IE) $classes[] = 'ie';
	else $classes[] = 'unknown';

	if($is_iphone) $classes[] = 'iphone';
	
	if ( isset( $post ) ) {
		$classes[] = 'body-' . $post->post_type ;
		$classes[] = 'body-' . $post->post_type . '-' . $post->post_name;
	}
	// Add class of group-blog to blogs with more than 1 published author.
	if ( is_multi_author() ) {
		$classes[] = 'theme-group-blog';
	}

	// Add class to singular pages.
	if ( is_singular() ) {
		$classes[] = 'theme-is-singular';
	}

	// Add class on front page.
	if ( is_front_page() && 'posts' !== get_option( 'show_on_front' ) ) {
		$classes[] = 'theme-front-page';
	}

	// Add a class if there is a custom header.
	if ( has_header_image() ) {
		$classes[] = 'theme-has-header-image';
	}
	
	// Add class of group-blog to blogs with more than 1 published author.
	if ( is_multi_author() ) {
		$classes[] = 'group-blog';
	}

	// Add class of hfeed to non-singular pages.
	if ( ! is_singular() ) {
		$classes[] = 'hfeed';
	}
	
	// add class if browser is ie
	if (preg_match("/(Trident\/(\d{2,}|7|8|9)(.*)rv:(\d{2,}))|(MSIE\ (\d{2,}|8|9)(.*)Tablet\ PC)|(Trident\/(\d{2,}|7|8|9))/", $_SERVER["HTTP_USER_AGENT"], $match) != 0) {
		$classes[] = 'ie';
    }
	
	// add class if user is looking on ios
	if (is_ios()){
		$classes[] = 'theme-is-ios';
	}
	
	// Add class if sidebar is used.
	if ( custom_check_for_sidebar() ) {
		$classes[] = 'theme-has-sidebar';
	}
	
	return $classes;
}

// Adds custom classes to the array of post classes.
function post_classes( $classes ) {
	global $wp_query, $post;
	// add slug- to post-type
	$post_type = get_post_type($post->ID);
	$key = array_search($post_type, $classes);
	if($key){
		$classes[$key] = 'slug-'.$post_type;
	}
	return $classes;
}

/**
 * Add "first" and "last" CSS classes to dynamic sidebar widgets. Also adds numeric index class for each widget (widget-1, widget-2, etc.)
 */
function widget_first_last_classes($params) {

	global $my_widget_num; // Global a counter array
	$this_id = $params[0]['id']; // Get the id for the current sidebar we're processing
	$arr_registered_widgets = wp_get_sidebars_widgets(); // Get an array of ALL registered widgets	

	if(!$my_widget_num) {// If the counter array doesn't exist, create it
		$my_widget_num = array();
	}

	if(!isset($arr_registered_widgets[$this_id]) || !is_array($arr_registered_widgets[$this_id])) { // Check if the current sidebar has no widgets
		return $params; // No widgets in this sidebar... bail early.
	}

	if(isset($my_widget_num[$this_id])) { // See if the counter array has an entry for this sidebar
		$my_widget_num[$this_id] ++;
	} else { // If not, create it starting with 1
		$my_widget_num[$this_id] = 1;
	}

	$class = 'class="widget-' . $my_widget_num[$this_id] . ' '; // Add a widget number class for additional styling options

	if($my_widget_num[$this_id] == 1) { // If this is the first widget
		$class .= 'widget-first ';
	} elseif($my_widget_num[$this_id] == count($arr_registered_widgets[$this_id])) { // If this is the last widget
		$class .= 'widget-last ';
	}
	if($my_widget_num[$this_id]%2==0){ // add even class
		$class .= 'widget-even ';
		
	}
	else {
		$class .= 'widget-odd '; // add odd class
	}
	$class .= 'clearfix ';
	
	//$params[0]['before_widget'] = str_replace('class="', $class, $params[0]['before_widget']); // Insert our new classes into "before widget"
	$params[0]['before_widget'] = preg_replace('/class=\"/', "$class", $params[0]['before_widget'], 1);	
	
	return $params;
}

/* MENU */
// add first and last class to menus and parent classes
function add_first_and_last_menu_class($items) {
	if(empty($items)) return $items;
	
    $items[1]->classes[] = 'first-menu-item';
    $items[count($items)]->classes[] = 'last-menu-item';
	
    $parents = array();
    foreach ( $items as $item ) {
        if ( $item->menu_item_parent && $item->menu_item_parent > 0 ) {
            $parents[] = $item->menu_item_parent;
        }
    }
  
    foreach ( $items as $item ) {
        if ( in_array( $item->ID, $parents ) ) {
            $item->classes[] = 'menu-parent-item';
        }
    }

    return $items;
}
// add slug class to menu item
function add_menu_slug_class( $items ) {
	foreach ( $items as $item ) {
		$slug_post = get_post($item->object_id);
		$slug = $slug_post->post_name;
		$item->classes[] = 'theme-menu-item-'.$slug; 
	}
	return $items;    
}

/*
 * Function for correcting classes if singular of custom post-type is selected.
 * Before it selected both singular and blog page as current_page_parent
 */
function wp_custom_nav_classes( $classes, $item ) {
	if( is_singular()){
		$classes = array_diff( $classes, array( 'current_page_parent' ) );    	
    }
	return $classes;
}

// redirect on page edit when post is published
function redirect_to_post_on_publish_or_save($location)
{
    if (isset($_POST['save']) || isset($_POST['publish'])) {
		if(get_post_type()!="post"){
			return admin_url('edit.php')."?post_type=".get_post_type();
		}
		else {
			return admin_url('edit.php');
		}
    }
	return $location;
}

if ( ! function_exists( 'custom_is_woocommerce_activated' ) ) {
	/**
	 * Query WooCommerce activation
	 */
	function custom_is_woocommerce_activated() {
		return class_exists( 'woocommerce' ) ? true : false;
	}
}

/**
 * Checks if the current page is a product archive
 * @return boolean
 */
function custom_is_woocommerce_product_archive() {
	if ( custom_is_woocommerce_activated() ) {
		if ( is_shop() || is_product_taxonomy() || is_product_category() || is_product_tag() ) {
			return true;
		} else {
			return false;
		}
	} else {
		return false;
	}
}

// Move Yoast to bottom
function yoasttobottom() {
	return 'low';
}

// add custom image size to admin media library 
function my_custom_sizes( $sizes ) {
    return array_merge( $sizes, array(
        //'blog-image' => __( 'Slika v blogu' ),
    ) );
}

// redirect first element from menu to first page under menu
function custom_page_template_redirect()
{
	global $moj_main_menu;
    if( is_page( ) )
    {
		if (have_posts()) {
			while (have_posts()) {
				the_post();
				
				$menuItems = wp_get_nav_menu_items($moj_main_menu);
				$parentMenuId = get_the_ID();
				$subMenuId = 0;

				$isTemplate = get_page_template_slug(get_the_ID());
				if(empty($isTemplate) && !empty($menuItems)){	
					foreach($menuItems as $menuItem) {
						if($menuItem->object_id == get_the_ID()) {
							$parentMenuId = $menuItem->ID;
						}
					}
					foreach($menuItems as $menuItem) {
						if($menuItem->menu_item_parent == $parentMenuId) {
							$subMenuId = $menuItem->object_id;
							break;
						}
					}
					if($subMenuId==0){
						// check for first subpage
						$page = get_post(get_the_ID());
						if(!empty($page)){
							$new_wp_query = new WP_Query();
							$all_wp_pages = $new_wp_query->query(array('post_type' => 'page', 'post_status' => 'publish', 'orderby' => 'menu_order title', 'posts_per_page' => -1));
							krsort($all_wp_pages); // reverse order, order=>ASC not working properly
							$page_children = get_page_children( $page->ID, $all_wp_pages );
							if(!empty($page_children)){
								$subMenuId = $page_children[0]->ID;
							}
						}
					}
					if($subMenuId>0){
						wp_redirect(get_permalink($subMenuId));
						exit;
					}
				}
			}
		}
	}
}

/**
* Disable the emoji's
*/
function disable_emojis() {
	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_emojis_tinymce' );
	add_filter( 'wp_resource_hints', 'disable_emojis_remove_dns_prefetch', 10, 2 );
}

/**
* Filter function used to remove the tinymce emoji plugin.
* 
* @param array $plugins 
* @return array Difference betwen the two arrays
*/
function disable_emojis_tinymce( $plugins ) {
	if ( is_array( $plugins ) ) {
		return array_diff( $plugins, array( 'wpemoji' ) );
	} else {
		return array();
	}
}

/**
* Remove emoji CDN hostname from DNS prefetching hints.
*
* @param array $urls URLs to print for resource hints.
* @param string $relation_type The relation type the URLs are printed for.
* @return array Difference betwen the two arrays.
*/
function disable_emojis_remove_dns_prefetch( $urls, $relation_type ) {
	if ( 'dns-prefetch' == $relation_type ) {
	/** This filter is documented in wp-includes/formatting.php */
	$emoji_svg_url = apply_filters( 'emoji_svg_url', 'https://s.w.org/images/core/emoji/2/svg/' );
	
	$urls = array_diff( $urls, array( $emoji_svg_url ) );
	}
	
	return $urls;
}

//* Dequeue Styles - Remove Font Awesome from WordPress theme
function custom_dequeue_font_awesome_style() {
	if(!is_admin()){
		wp_dequeue_style( 'fontawesome' );
      	wp_deregister_style( 'fontawesome' );	
	}      
}

/**
 * Remove the Color Picker plugin from tinyMCE. This will
 * prevent users from adding custom colors. Note, the default color
 * palette is still available (and customizable by developers) via
 * textcolor_map using the tiny_mce_before_init hook.
 * 
 * @param array $plugins An array of default TinyMCE plugins.
 */
function wpse_tiny_mce_remove_custom_colors( $plugins ) {
    foreach ( $plugins as $key => $plugin_name ) {
        if ( 'colorpicker' === $plugin_name ) {
            unset( $plugins[ $key ] );
            return $plugins;            
        }
    }
    return $plugins;            
}

/**
 * Customize TinyMCE with colors, formats and block formats
 */
function wp_custom_tinymce_settings($init) {
	// Add custom colors to TinyMCE
	global $tinymce_custom_colours;
	$default_colours = '"000000", "Black",
                      	"993300", "Burnt orange",
						"333300", "Dark olive",
						"003300", "Dark green",
						"003366", "Dark azure",
						"000080", "Navy Blue",
						"333399", "Indigo",
						"333333", "Very dark gray",
						"800000", "Maroon",
						"FF6600", "Orange",
						"808000", "Olive",
						"008000", "Green",
						"008080", "Teal",
						"0000FF", "Blue",
						"666699", "Grayish blue",
						"808080", "Gray",
						"FF0000", "Red",
						"FF9900", "Amber",
						"99CC00", "Yellow green",
						"339966", "Sea green",
						"33CCCC", "Turquoise",
						"3366FF", "Royal blue",
						"800080", "Purple",
						"999999", "Medium gray",
						"FF00FF", "Magenta",
						"FFCC00", "Gold",
						"FFFF00", "Yellow",
						"00FF00", "Lime",
						"00FFFF", "Aqua",
						"00CCFF", "Sky blue",
						"993366", "Red violet",
						"FFFFFF", "White",
						"FF99CC", "Pink",
						"FFCC99", "Peach",
						"FFFF99", "Light yellow",
						"CCFFCC", "Pale green",
						"CCFFFF", "Pale cyan",
						"99CCFF", "Light sky blue",
						"CC99FF", "Plum"';
	
	// build colour grid default+custom colors
  	//$init['textcolor_map'] = '['.$default_colours.','.$custom_colours.']';
  	$init['textcolor_map'] = '['.$tinymce_custom_colours.']';
	// set rows and columns for colors
	$init['textcolor_rows'] = 1;
	$init['textcolor_cols'] = 3;  
	
	// Define the style_formats array
	$style_formats = array(  
		// Each array child is a format with it's own settings		
		array(  
			'title' => 'gumb',  
			'block' => 'div',
			'classes' => 'wp-custom-readmore',
			'wrapper' => true,
		),		
		array(  
			'title' => 'Naslov 1 izgled',
			'inline' => 'span',
			'classes' => 'we-custom-title'
		),	
		array(  
			'title' => 'Modra barva',
			'inline' => 'span',
			'classes' => 'we-blue',			
		),		
	);  
	// Insert the array, JSON ENCODED, into 'style_formats'
	$init['style_formats'] = json_encode( $style_formats );
	
	// Add block format elements you want to show in dropdown
	// Modify TinyMCE editor to remove H1.
	$init['block_formats'] = 'Paragraph=p;Heading 2=h2;Heading 3=h3;Heading 4=h4;Heading 5=h5;Heading 6=h6;Pre=pre';

	return $init;
}

// Callback function to insert 'styleselect' into the $buttons array
function my_mce_buttons_2( $buttons ) {
	array_unshift( $buttons, 'styleselect' );
	return $buttons;
}

/**
 * All pre_get_posts options in one place
 */
function custom_pre_get_posts_options($query)
{
	// Change category for posts page (novice)
    if( !is_admin() && $query->is_main_query() && ($query->is_home() || $query->is_archive()) ){
        //$query->set( 'category_name', 'novice' );
		//$query->set( 'posts_per_page', 30 );
    }
		
	return $query;
}

function wp_custom_post_gallery($output, $attr)
{
	global $gallery_override_size, $gallery_override_link, $gallery_override_columns;
	$post = get_post();

	static $instance = 0;
	$instance++;

	if ( ! empty( $attr['ids'] ) ) {
		// 'ids' is explicitly ordered, unless you specify otherwise.
		if ( empty( $attr['orderby'] ) ) {
			$attr['orderby'] = 'post__in';
		}
		$attr['include'] = $attr['ids'];
	}

	$html5 = current_theme_supports( 'html5', 'gallery' );
	$atts = shortcode_atts( array(
		'order'      => 'ASC',
		'orderby'    => 'menu_order ID',
		'id'         => $post ? $post->ID : 0,
		'itemtag'    => $html5 ? 'figure'     : 'dl',
		'icontag'    => $html5 ? 'div'        : 'dt',
		'captiontag' => $html5 ? 'figcaption' : 'dd',
		'columns'    => 4,
		'size'       => 'thumbnail',
		'include'    => '',
		'exclude'    => '',
		'link'       => ''
	), $attr, 'gallery' );
	
	// override size
	if($gallery_override_size){
		$atts['size'] = $gallery_override_size;
	}
	// override link
	if($gallery_override_link){
		$atts['link'] = $gallery_override_link;
	}
	// override columns
	if($gallery_override_columns){
		$atts['columns'] = $gallery_override_columns;
	}
	
	$id = intval( $atts['id'] );

	if ( ! empty( $atts['include'] ) ) {
		$_attachments = get_posts( array( 'include' => $atts['include'], 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );

		$attachments = array();
		foreach ( $_attachments as $key => $val ) {
			$attachments[$val->ID] = $_attachments[$key];
		}
	} elseif ( ! empty( $atts['exclude'] ) ) {
		$attachments = get_children( array( 'post_parent' => $id, 'exclude' => $atts['exclude'], 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
	} else {
		$attachments = get_children( array( 'post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
	}

	if ( empty( $attachments ) ) {
		return '';
	}

	if ( is_feed() ) {
		$output = "\n";
		foreach ( $attachments as $att_id => $attachment ) {
			$output .= wp_get_attachment_link( $att_id, $atts['size'], true ) . "\n";
		}
		return $output;
	}

	$itemtag = tag_escape( $atts['itemtag'] );
	$captiontag = tag_escape( $atts['captiontag'] );
	$icontag = tag_escape( $atts['icontag'] );
	$valid_tags = wp_kses_allowed_html( 'post' );
	if ( ! isset( $valid_tags[ $itemtag ] ) ) {
		$itemtag = 'dl';
	}
	if ( ! isset( $valid_tags[ $captiontag ] ) ) {
		$captiontag = 'dd';
	}
	if ( ! isset( $valid_tags[ $icontag ] ) ) {
		$icontag = 'dt';
	}

	$columns = intval( $atts['columns'] );
	$itemwidth = $columns > 0 ? floor(100/$columns) : 100;
	$float = is_rtl() ? 'right' : 'left';

	$selector = "gallery-{$instance}";

	$gallery_style = '';

	/**
	 * Filters whether to print default gallery styles.
	 *
	 * @since 3.1.0
	 *
	 * @param bool $print Whether to print default gallery styles.
	 *                    Defaults to false if the theme supports HTML5 galleries.
	 *                    Otherwise, defaults to true.
	 */
	if ( apply_filters( 'use_default_gallery_style', ! $html5 ) ) {
		$gallery_style = "
		<style type='text/css'>
			#{$selector} {
				margin: auto;
			}
			#{$selector} .gallery-item {
				float: {$float};
				margin-top: 10px;
				text-align: center;
				width: {$itemwidth}%;
			}
			#{$selector} img {
				border: 2px solid #cfcfcf;
			}
			#{$selector} .gallery-caption {
				margin-left: 0;
			}
			/* see gallery_shortcode() in wp-includes/media.php */
		</style>\n\t\t";
	}

	$size_class = sanitize_html_class( $atts['size'] );
	$gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";

	/**
	 * Filters the default gallery shortcode CSS styles.
	 *
	 * @since 2.5.0
	 *
	 * @param string $gallery_style Default CSS styles and opening HTML div container
	 *                              for the gallery shortcode output.
	 */
	$output = apply_filters( 'gallery_style', $gallery_style . $gallery_div );

	$i = 0;
	foreach ( $attachments as $id => $attachment ) {

		$attr = ( trim( $attachment->post_excerpt ) ) ? array( 'aria-describedby' => "$selector-$id" ) : '';
		if ( ! empty( $atts['link'] ) && 'file' === $atts['link'] ) {
			//$image_output = wp_get_attachment_link( $id, 'thumbnail', false, false, false, $attr );
			$image_output = wp_get_attachment_link( $id, $atts['size'], false, false, false, $attr );
			// add title attribute (and caption if not empty)
			$image_output = str_replace('<a href', '<a title="'. wptexturize($attachment->post_title) . ($captiontag && trim($attachment->post_excerpt)?' - '.wptexturize($attachment->post_excerpt):"") .'" href', $image_output);
		} elseif ( ! empty( $atts['link'] ) && 'none' === $atts['link'] ) {
			$image_output = wp_get_attachment_image( $id, $atts['size'], false, $attr );
		} else {
			$image_output = wp_get_attachment_link( $id, $atts['size'], true, false, false, $attr );
		}
		$image_meta  = wp_get_attachment_metadata( $id );

		$orientation = '';
		if ( isset( $image_meta['height'], $image_meta['width'] ) ) {
			$orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';
		}
		$output .= "<{$itemtag} class='gallery-item'>";
		$output .= "
			<{$icontag} class='gallery-icon {$orientation}'>
				$image_output
			</{$icontag}>";
		if ( $captiontag && trim($attachment->post_excerpt) ) {
			$output .= "
				<{$captiontag} class='wp-caption-text gallery-caption' id='$selector-$id'>
				<span class='wp-caption-text-wrap'>
				" . wptexturize($attachment->post_excerpt) . "
				</span>
				</{$captiontag}>";
		}
		$output .= "</{$itemtag}>";
		if ( ! $html5 && $columns > 0 && ++$i % $columns == 0 ) {
			$output .= '<br style="clear: both" />';
		}
	}

	if ( ! $html5 && $columns > 0 && $i % $columns !== 0 ) {
		$output .= "
			<br style='clear: both' />";
	}

	$output .= "
		</div>\n";

	return $output;   	
}

// add custom query var
function add_custom_query_vars_filter( $vars ){
    $vars[] = 'tpage';
	return $vars;
}

/**
 * Function to check if page has children
 */
function page_has_children() {
    global $post;

    $children = get_pages( array( 'child_of' => $post->ID ) );
    if( count( $children ) == 0 ) {
        return false;
    } else {
        return true;
    }
}

// function to get id by page slug
function get_id_by_slug($page_slug) {
	$page = get_page_by_path($page_slug);
	if ($page) {
		return $page->ID;
	} else {
		return null;
	}
}

function theme_get_archives_link( $link_html ) {
    global $wp;
    static $current_url;
    if ( empty( $current_url ) ) {
        $current_url = add_query_arg( $_SERVER['QUERY_STRING'], '', home_url( $wp->request ) );
    }
    if ( stristr( $link_html, $current_url ) !== false ) {
        $link_html = preg_replace( '/(<[^\s>]+)/', '\1 class="current"', $link_html, 1 );
    }
    return $link_html;
}

// add inline jquery script
function theme_prefix_enqueue_script() {
   if ( ! wp_script_is( 'jquery', 'done' ) ) {
     wp_enqueue_script( 'jquery' );
   }
   wp_add_inline_script( 'jquery-migrate', "" );
}

if(!function_exists('is_ios')){
	function is_ios() {
    	return wp_is_mobile() && preg_match( '/iPad|iPod|iPhone/', $_SERVER['HTTP_USER_AGENT'] );
	}
}

/* Add attribute data-lightbox-gallery for nivo lightbox effect and multiple images (next/prev buttons) */
function add_foogallery_link_rel($attr, $args, $attachment) {
	$attr['data-lightbox-gallery'] = 'gallery';
	return $attr;
}

function remove_archive_title_labels( $title ) {
    if ( is_category() ) {
        $title = single_cat_title( '', false );
    } elseif ( is_tag() ) {
        $title = single_tag_title( '', false );
    } elseif ( is_author() ) {
        $title = '<span class="vcard">' . get_the_author() . '</span>';
    } elseif ( is_post_type_archive() ) {
        $title = post_type_archive_title( '', false );
    } elseif ( is_tax() ) {
        $title = single_term_title( '', false );
    }
  
    return $title;
}

// clean shortcodes
function wp_custom_clean_shortcodes($content){   
	$array = array (
		'<p>[' => '[', 
		']</p>' => ']', 
		']<br />' => ']'
	);
	$content = strtr($content, $array);
	return $content;
}

if(!function_exists('wp_custom_breadcrumbs')){
	function wp_custom_breadcrumbs()
	{
		global $use_breadcrumbs;
		if(is_front_page() || !$use_breadcrumbs) return;
		?>
		<div class="breadcrumbs-wrap">
			<div class="breadcrumbs" typeof="BreadcrumbList" vocab="http://schema.org/">
				<?php if(function_exists('bcn_display')){
					bcn_display();
				} ?>
			</div>
		</div>
		<?php
	}
}

function custom_excerpt_max_charlength($charlength, $return = true) {
	$excerpt = get_the_excerpt();
	$charlength++;
	$html = '';
	
	if ( mb_strlen( $excerpt ) > $charlength ) {
		$subex = mb_substr( $excerpt, 0, $charlength - 5 );
		$exwords = explode( ' ', $subex );
		$excut = - ( mb_strlen( $exwords[ count( $exwords ) - 1 ] ) );
		if ( $excut < 0 ) {
			$html .= mb_substr( $subex, 0, $excut );
		} else {
			$html .= $subex;
		}
		$html .= '...';
	} else {
		$html .= $excerpt;
	}
	$html = trim($html);
	$tag = (is_front_page())?'span':'div';
	$html = '<'.$tag.' class="excerpt-wrap">'.$html.'</'.$tag.'>';
	if($return){
		return $html;
	}
	else {
		echo $html;
	}
}

// add class to main menu links
function custom_link_atts($atts) {
  $atts['class'] = "menu-link";
  return $atts;
}