<?php


//==========================================================================
//  Sidebars
//==========================================================================

if ( function_exists('register_sidebars') )

	register_sidebars(2,array(
		'before_widget' => '<aside id="%1$s" class="widget %2$s">',
		'after_widget'  => '</aside>',
		'before_title'  => '<h3 class="widget-title">',
		'after_title'   => '</h3>',
	));

	register_sidebar(array(
		'name'=>'ヘッダーバナー',
		'id'=>'bigbanner_top',
		'before_widget' => '<div id="%1$s" class="widget %2$s bigbanner_top">',
		'after_widget'  => '</div>',
		'before_title'  => '<h3 class="widget-title">',
		'after_title'   => '</h3>'
	));

	register_sidebar(array(
		'name'=>'トップ メインカラム上',
		'id'=>'top_main_top',
		'before_widget' => '<div id="%1$s" class="widget %2$s">',
		'after_widget'  => '</div>',
		'before_title'  => '<h3 class="widget-title">',
		'after_title'   => '</h3>'
	));

	register_sidebar(array(
		'name'=>'トップ メインカラム上（1ページ目のみ）',
		'id'=>'top_main_top-1st',
		'before_widget' => '<div id="%1$s" class="widget %2$s">',
		'after_widget'  => '</div>',
		'before_title'  => '<h3 class="widget-title">',
		'after_title'   => '</h3>'
	));

	register_sidebar(array(
		'name'=>'トップ メインカラム下',
		'id'=>'top_main_bottom',
		'before_widget' => '<div id="%1$s" class="widget %2$s">',
		'after_widget'  => '</div>',
		'before_title'  => '<h3 class="widget-title">',
		'after_title'   => '</h3>'
	));

	register_sidebar(array(
		'name'=>'記事 メインカラム上',
		'id'=>'single_main_top',
		'before_widget' => '<div id="%1$s" class="widget %2$s">',
		'after_widget'  => '</div>',
		'before_title'  => '<h3 class="widget-title">',
		'after_title'   => '</h3>'
	));

	register_sidebar(array(
		'name'=>'記事 本文上',
		'id'=>'single_main_post_content_top',
		'before_widget' => '<div id="%1$s" class="widget %2$s single_main_post_content_top">',
		'after_widget'  => '</div>',
		'before_title'  => '<h3 class="h3">',
		'after_title'   => '</h3>'
	));

	register_sidebar(array(
		'name'=>'記事 本文下',
		'id'=>'single_main_post_content_bottom',
		'before_widget' => '<div id="%1$s" class="widget %2$s single_main_post_content_bottom">',
		'after_widget'  => '</div>',
		'before_title'  => '<h3 class="h3">',
		'after_title'   => '</h3>'
	));

	register_sidebar(array(
		'name'=>'記事 メインカラム下',
		'id'=>'single_main_bottom',
		'before_widget' => '<div id="%1$s" class="widget %2$s single_main_bottom">',
		'after_widget'  => '</div>',
		'before_title'  => '<h3 class="widget-title">',
		'after_title'   => '</h3>'
	));

	register_sidebar(array(
		'name'=>'フッターバナー',
		'id'=>'bigbanner_bottom',
		'before_widget' => '<div id="%1$s" class="widget cl %2$s bigbanner_bottom">',
		'after_widget'  => '</div>',
		'before_title'  => '<h3 class="widget-title">',
		'after_title'   => '</h3>'
	));


//==========================================================================
//  Content Width
//==========================================================================

if ( ! isset( $content_width ) )
	$content_width = 960;


//==========================================================================
//  Editor Style
//==========================================================================

add_editor_style('style.css');
add_editor_style('style-core.php');
add_editor_style('ipfw/style.css');
add_editor_style('editor-style.css');
if ( ! isset( $content_width ) ) $content_width = 690;
function custom_editor_settings( $initArray ){
	$initArray['body_class'] = 'entry-content';
	return $initArray;
}
add_filter( 'tiny_mce_before_init', 'custom_editor_settings' );


//==========================================================================
//  Eye catch
//==========================================================================

add_theme_support( 'post-thumbnails' );


//==========================================================================
//  Posts and Comments RSS feed links to <head>.
//==========================================================================

add_theme_support( 'automatic-feed-links' );


//==========================================================================
//  Custom background
//==========================================================================

add_custom_background();


//==========================================================================
//  Custom menu
//==========================================================================

register_nav_menus( array(
	'header-navi' => 'Header Navigation',
	'gloval-navi' => 'Global Navigation',
	'footer-navi' => 'Footer Navigation',
) );
function no_menu(){
	echo " ";
}


//==========================================================================
//  Comment replay
//==========================================================================

if ( is_singular() ) wp_enqueue_script( 'comment-reply' );


//==========================================================================
//  Custom header
//==========================================================================

function myd_custom_header_setup() {
	$args = array(
		'default-text-color'     => '333333',
		'default-image'          => '',
		'width'                  => '',
		'height'                 => '',
		'flex-width'             => false,
		'flex-height'            => true,
		'wp-head-callback'       => 'myd_header_style',
		'admin-head-callback'    => 'myd_admin_header_style',
		'admin-preview-callback' => 'myd_admin_header_image'
	);

	$args = apply_filters( 'myd_custom_header_args', $args );

	if ( function_exists( 'wp_get_theme' ) ) :
		// Add support for custom headers.
		add_theme_support( 'custom-header', $args );
	else :
		// Compat: Versions of WordPress prior to 3.4.
		define( 'HEADER_TEXTCOLOR', $args['default-text-color'] );
		define( 'HEADER_IMAGE', $args['default-image'] );
		define( 'HEADER_IMAGE_WIDTH', $args['width'] );
		define( 'HEADER_IMAGE_HEIGHT', $args['height'] );
		add_custom_image_header( $args['wp-head-callback'], $args['admin-head-callback'], $args['admin-preview-callback'] );
	endif;

}
add_action( 'after_setup_theme', 'myd_custom_header_setup' );

if ( ! function_exists( 'myd_header_style' ) ) :
/* Styles the header text displayed on the blog.  */
function myd_header_style() {
	$text_color = get_header_textcolor();

	// If no custom options for text are set, let's bail.
	if ( $text_color == HEADER_TEXTCOLOR )
		return;

	// If we get this far, we have custom styles. Let's do this.
	?>
	<style type="text/css">
	<?php
		// Has the text been hidden?
		if ( 'blank' == $text_color ) :
	?>
		.site-title,
		.site-description {
			position: absolute !important;
			clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
			clip: rect(1px, 1px, 1px, 1px);
		}
	<?php
		// If the user has set a custom color for the text use that
		else :
	?>
		.site-title a,
		.site-description {
			color: #<?php echo $text_color; ?> !important;
			text-shadow: none !important;
		}
	<?php endif; ?>
	</style>
	<?php
}
endif; // myd_header_style

if ( ! function_exists( 'myd_admin_header_style' ) ) :
/* Styles the header image displayed on the Appearance > Header admin panel. */
function myd_admin_header_style() {
?>
	<style type="text/css">
	.appearance_page_custom-header #headimg {
		border: none;
		max-width: 1260px;
		min-height: 48px;
	}
	#headimg h1 {
		font-size: 28px;
		line-height: 1.333;
	}
	#headimg h1 a {
		color: #333;
		text-decoration: none;
	}
	#headimg img {
		vertical-align: middle;
	}
	</style>
<?php
}
endif; // myd_admin_header_style

if ( ! function_exists( 'myd_admin_header_image' ) ) :
/* Outputs markup to be displayed on the Appearance > Header admin panel. */
function myd_admin_header_image() { ?>
	<div id="headimg">
		<?php if ( get_header_image() ) : ?>
		<img src="<?php header_image(); ?>" alt="">
		<?php endif; ?>
		<h1 class="displaying-header-text"><a id="name"<?php echo sprintf( ' style="color:#%s;"', get_header_textcolor() ); ?> onclick="return false;" href="<?php echo esc_url( home_url( '/' ) ); ?>"><?php bloginfo( 'name' ); ?></a></h1>
	</div>
<?php }
endif; // myd_admin_header_image


//==========================================================================
//  パンくずリスト
//==========================================================================

function breadcrumb(){
	global $post;
	if(!is_home()&&!is_admin()){
		$str.= '<div class="breadcrumb">';
		$str.= '<ol>';
		$str.= '<li itemscope itemtype="http://data-vocabulary.org/Breadcrumb"><a itemprop="url" href="'. home_url() .'/"><span itemprop="title">HOME</span></a></li>';
		if(is_search()){
			$str.='<li>「'. get_search_query() .'」で検索した結果</li>';
		} elseif(is_tag()){
			$str.='<li>タグ : '. single_tag_title( '' , false ). '</li>';
		} elseif(is_404()){
			$str.='<li>404 Not found</li>';
		} elseif(is_date()){
			if(get_query_var('day') != 0){
				$str.='<li itemscope itemtype="http://data-vocabulary.org/Breadcrumb"><a itemprop="url" href="'. get_year_link(get_query_var('year')). '"><span itemprop="title">' . get_query_var('year'). '年</span></a></li>';
				$str.='<li itemscope itemtype="http://data-vocabulary.org/Breadcrumb"><a itemprop="url" href="'. get_month_link(get_query_var('year'), get_query_var('monthnum')). '"><span itemprop="title">'. get_query_var('monthnum') .'月</span></a></li>';
				$str.='<li>'. get_query_var('day'). '日</li>';
			} elseif(get_query_var('monthnum') != 0){
				$str.='<li itemscope itemtype="http://data-vocabulary.org/Breadcrumb"><a itemprop="url" href="'. get_year_link(get_query_var('year')) .'"><span itemprop="title">'. get_query_var('year') .'年</span></a></li>';
				$str.='<li>'. get_query_var('monthnum'). '月</li>';
			} else {
				$str.='<li>'. get_query_var('year') .'年</li>';
			}
		} elseif(is_category()) {
			$cat = get_queried_object();
			if($cat -> parent != 0){
				$ancestors = array_reverse(get_ancestors( $cat -> cat_ID, 'category' ));
				foreach($ancestors as $ancestor){
					$str.='<li itemscope itemtype="http://data-vocabulary.org/Breadcrumb"><a itemprop="url" href="'. get_category_link($ancestor) .'"><span itemprop="title">'. get_cat_name($ancestor) .'</span></a></li>';
				}
			}
			$str.= '<li itemscope itemtype="http://data-vocabulary.org/Breadcrumb"><a itemprop="url" href="'. get_category_link($cat -> cat_ID).'"><span itemprop="title">'. $cat -> name .'</span></a></li>';
		} elseif(is_author()){
			$str .='<li>投稿者 : '. get_the_author_meta('display_name', get_query_var('author')).'</li>';
		} elseif(is_page()){
			if($post -> post_parent != 0 ){
				$ancestors = array_reverse(get_post_ancestors( $post->ID ));
				foreach($ancestors as $ancestor){
					$str.='<li itemscope itemtype="http://data-vocabulary.org/Breadcrumb"><a itemprop="url" href="'. get_permalink($ancestor).'"><span itemprop="title">'. get_the_title($ancestor) .'</span></a></li>';
				}
			}
			$str.= '<li itemscope itemtype="http://data-vocabulary.org/Breadcrumb"><a itemprop="url" href="'. get_permalink($post -> ID).'"><span itemprop="title">'. $post -> post_title .'</span></a></li>';
		} elseif(is_attachment()){
			if($post -> post_parent != 0 ){
				$str.= '<li itemscope itemtype="http://data-vocabulary.org/Breadcrumb"><a itemprop="url" href="'. get_permalink($post -> post_parent).'"><span itemprop="title">'. get_the_title($post -> post_parent) .'</span></a></li>';
			}
			$str.= '<li itemscope itemtype="http://data-vocabulary.org/Breadcrumb"><a itemprop="url" href="'. get_permalink($post -> ID).'"><span itemprop="title">' . $post -> post_title . '</span></a></li>';
		} elseif(is_single()){
			$categories = get_the_category($post->ID);
			$cat = $categories[0];
			if($cat -> parent != 0){
				$ancestors = array_reverse(get_ancestors( $cat -> cat_ID, 'category' ));
				foreach($ancestors as $ancestor){
					$str.='<li itemscope itemtype="http://data-vocabulary.org/Breadcrumb"><a itemprop="url" href="'. get_category_link($ancestor).'"><span itemprop="title">'. get_cat_name($ancestor). '</span></a></li>';
				}
			}
			$str.='<li itemscope itemtype="http://data-vocabulary.org/Breadcrumb"><a itemprop="url" href="'. get_category_link($cat -> term_id). '"><span itemprop="title">'. $cat-> cat_name . '</span></a></li>';
			$str.= '<li itemscope itemtype="http://data-vocabulary.org/Breadcrumb"><a itemprop="url" href="'. get_permalink($post -> ID).'"><span itemprop="title">'. $post -> post_title .'</span></a></li>';
		} else{
			$str.='<li>'. wp_title('', false) .'</li>';
		}
		$str.='</ol>';
		$str.='</div>';
	}
	echo $str;
}

//==========================================================================
//  ページャー
//==========================================================================

function pagination($pages = '', $range = 4)
{
	$showitems = ($range * 2)+1; 
	global $paged;
	if(empty($paged)) $paged = 1;
	if($pages == '')
	{
		global $wp_query;
		$pages = $wp_query->max_num_pages;
		if(!$pages)
		{
			$pages = 1;
		}
	}
	if(1 != $pages)
	{
		echo "<div class=\"page-navi\">";
		if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "<a href='".get_pagenum_link(1)."'>&laquo; 最初</a>";
		if($paged > 1 && $showitems < $pages) echo "<a href='".get_pagenum_link($paged - 1)."'>&lsaquo; 前へ</a>";
		for ($i=1; $i <= $pages; $i++)
		{
			if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
			{
				echo ($paged == $i)? "<span class=\"current\">".$i."</span>":"<a href='".get_pagenum_link($i)."' class=\"inactive\">".$i."</a>";
			}
		}
		if ($paged < $pages && $showitems < $pages) echo "<a href=\"".get_pagenum_link($paged + 1)."\">次へ &rsaquo;</a>";
		if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($pages)."'>最後 &raquo;</a>";
		echo "<span class=\"pages\">".$paged." / ".$pages."</span></div>\n";
	}
}


//==========================================================================
//  記事のタイトルがないときに、(no title)を表示
//==========================================================================

function set_the_title($title = "") {
	$sNoTitle = "(no title)";

	if(strlen($title) === 0) {
		return $sNoTitle;
	}
	return $title;
}
add_filter('the_title', 'set_the_title');


//==========================================================================
//  抜粋の長さを変更する
//==========================================================================
function custom_excerpt_length($length) {
	return 140;
}
add_filter('excerpt_length', 'custom_excerpt_length');


//==========================================================================
//  「もっと見る」リンクの文字省略時の文字列を変更
//==========================================================================
function new_excerpt_more($more) {
	return ' ‥‥';
}
add_filter('excerpt_more', 'new_excerpt_more');


//==========================================================================
//  続きを読むのハッシュを消す
//==========================================================================

function remove_more_jump_link($link) {
	$offset = strpos($link, '#more-');
	if ($offset) {
		$end = strpos($link, '"',$offset);
	}
	if ($end) {
		$link = substr_replace($link, '', $offset, $end-$offset);
	}
	return $link;
}
add_filter('the_content_more_link', 'remove_more_jump_link');


//==========================================================================
//  コメントのURL自動リンク機能OFF
//==========================================================================

remove_filter('comment_text', 'make_clickable', 9);


//==========================================================================
//  自動整形wpautop()の実行順を変更（無駄な<br />や<p>タグが入るのを防止
//==========================================================================

// remove_filter( 'the_content', 'wpautop' );
// add_filter( 'the_content', 'wpautop' , 12);


//==========================================================================
//  リンクウィジェットのリンクにnofollowを追加
//==========================================================================

function no_follow( $links ) {
	foreach($links as $link) {
		 $link->link_rel .= ' nofollow';
		 $link->link_rel = trim($link->link_rel);
	}
		 return $links;
}
add_filter('get_bookmarks', 'no_follow');


//==========================================================================
//  recentcommentsを削除
//==========================================================================

function remove_recent_comments_style() {
	global $wp_widget_factory;
	remove_action( 'wp_head', array( $wp_widget_factory->widgets['WP_Widget_Recent_Comments'], 'recent_comments_style' ) );
}
add_action( 'widgets_init', 'remove_recent_comments_style' );


//==========================================================================
//メディア挿入時のデフォルトのリンク先を「なし」に設定する
//==========================================================================

function webshufu_default_noimagelink() {
	$webshufu_default_imagelink = get_option( 'image_default_link_type' );

	if ($webshufu_default_imagelink !== 'none') {
		update_option('image_default_link_type', 'none');
	}
}
add_action('admin_init', 'webshufu_default_noimagelink', 10);


//==========================================================================
//  投稿一覧や固定ページ一覧のテーブルにアイキャッチの列を追加
//==========================================================================

if ( !function_exists('AddThumbColumn') && function_exists('add_theme_support') ) {

		add_theme_support('post-thumbnails', array( 'post', 'page' ) );

		function AddThumbColumn($cols) {
				$cols['thumbnail'] = __('Thumbnail');
				return $cols;
		}

		function AddThumbValue($column_name, $post_id) {
				$width = (int) 35;
				$height = (int) 35;

				if ( 'thumbnail' == $column_name ) {
						$thumbnail_id = get_post_meta( $post_id, '_thumbnail_id', true );
						$attachments = get_children( array('post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image') );
						if ($thumbnail_id)
						$thumb = wp_get_attachment_image( $thumbnail_id, array($width, $height), true );
						elseif ($attachments) {
								foreach ( $attachments as $attachment_id => $attachment ) {
										$thumb = wp_get_attachment_image( $attachment_id, array($width, $height), true );
								}
						}
						if ( isset($thumb) && $thumb ) {
								echo $thumb;
						} else {
								echo __('None');
						}
				}
		}

		// 投稿
		add_filter( 'manage_posts_columns', 'AddThumbColumn' );
		add_action( 'manage_posts_custom_column', 'AddThumbValue', 10, 2 );

		// 固定ページ
		add_filter( 'manage_pages_columns', 'AddThumbColumn' );
		add_action( 'manage_pages_custom_column', 'AddThumbValue', 10, 2 );
}


//==========================================================================
//  タグクラウドの設定
//==========================================================================

function myd_tag_cloud_args( $args ) {
	$my_args = array(
	'number' => '45',
	'largest' => '13'
	);
	$args = wp_parse_args( $args, $my_args );
	return $args;
}
add_filter( 'widget_tag_cloud_args', 'myd_tag_cloud_args' );


//==========================================================================
//  titleタグの設定
//==========================================================================

function ip5_wp_title( $title, $sep ) {
	global $paged, $page;

	if ( is_feed() ) {
		return $title;
	}

	// Add the site name.
	$title .= get_bloginfo( 'name', 'display' );

	// Add the site description for the home/front page.
	$site_description = get_bloginfo( 'description', 'display' );
	if ( $site_description && ( is_home() || is_front_page() ) ) {
		$title = "$title $sep $site_description";
	}

	// Add a page number if necessary.
	if ( $paged >= 2 || $page >= 2 ) {
		$title = "$title $sep " . sprintf( __( 'Page %s', 'ip5' ), max( $paged, $page ) );
	}

	return $title;
}
add_filter( 'wp_title', 'ip5_wp_title', 10, 2 );

//==========================================================================
//  JSON-LDを記述
//==========================================================================

add_action('wp_footer','myd_insert_json_ld');

function myd_get_article () {
	if (is_page() || is_single()) {
		if (have_posts()) : while (have_posts()) : the_post();
			$contentArr['@type'] = 'Article';
			$contentArr['headline'] = get_the_title();
			$time = strtotime( get_the_time('c') );
			$contentArr['datePublished'] = date( 'c', $time );

			$contentArr['image'] = myd_post_thumbnail();
			$contentArr['url'] = get_permalink();
			$contentArr['articleBody'] = get_the_content();

			$contentArr['author']['@type'] = 'Person';
			$contentArr['author']['name']  = get_the_author();

			$contentArr['publisher']['@type'] = 'Organization';
			$contentArr['publisher']['name']  = get_bloginfo('name');

		endwhile; endif;
		rewind_posts();
		return $contentArr;
	}
}

function myd_catch_that_image() {
	global $post;
	if ( preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches ) ) {
		$myd_first_img = $matches[1][0];
	} else {
		$myd_first_img = false;
	}
	return $myd_first_img;
}

function myd_post_thumbnail() {
	if ( get_post_thumbnail_id() ) {
		$myd_img = wp_get_attachment_url( get_post_thumbnail_id() );
	} elseif( myd_catch_that_image() ) {
		$myd_img = myd_catch_that_image();
	} else {
		$myd_img = false;
	}

	if (!$myd_img) {
		$myd_img = get_template_directory_uri(). "ipfw/img/dummyimage.png";
	}

	return $myd_img;
}

function myd_get_search_Action($homeUrl){
	$contentArr = array(
		"@type"      => "SearchAction",
		"target"     => "{$homeUrl}/?s={search_term}",
		"query-input"=> "required name=search_term"
	);
	return $contentArr;
}

function myd_insert_json_ld(){
	$homeUrl = get_home_url();

	$contentArr = array(
		"@context" => "http://schema.org",
	);
	if (is_front_page()) {
		$contentArr['@type']            = "WebSite";
		$contentArr['url']              = $homeUrl;
		$contentArr['potentialAction']  = myd_get_search_Action($homeUrl);
	} elseif (is_page() || is_single()) {
		$contentArr['@graph'] = myd_get_article();
	}

	$jsonld = json_encode($contentArr, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT);

	echo '<script type="application/ld+json">';
	echo $jsonld;
	echo '</script>';
}

//==========================================================================
//  ビジュアルエディタにボタンを追加
//==========================================================================

function ilc_mce_buttons($buttons){
	array_push($buttons, "backcolor", "code", "fontsizeselect");
	return $buttons;
}
add_filter("mce_buttons", "ilc_mce_buttons");


//==========================================================================
//  投稿タイトルを特別に設定
//==========================================================================

/* １．カスタムフィールドを追加する記述 */
function customh1_add_custom_box() {
	add_meta_box('customh1', '投稿タイトルを特別に設定する', 'customh1_inner_custom_box', 'post', 'normal', 'high');
	add_meta_box('customh1', '投稿タイトルを特別に設定する', 'customh1_inner_custom_box', 'page', 'normal', 'high');
}

/* ２．カスタムフィールドボックス内のHTMLを記述 */
function customh1_inner_custom_box() {
	echo '<p>通常の投稿タイトルとは別に特別な投稿タイトル（大見出し）をつけたい場合はここに記述してください。その場合、個別ページでは、ここに記述した文章が投稿タイトルになり、headerの&lt;title&gt;タグには通常の投稿タイトルが入ります。</p>';
	if (isset($_GET['post'])) {
		$customh1_array = get_post_meta( $_GET['post'], 'customh1');
		if (isset($customh1_array[0])) {
			$customh1 = $customh1_array[0];
		} else {
			$customh1 = "";
		}
	} else {
		$customh1 = "";
	}

	$res = "<input type=\"text\" name=\"customh1\" value=\"".htmlspecialchars($customh1)."\" size=\"64\" maxlength=\"64\" />";
	echo $res;
}

/* ３．設定したカスタムフィールドの値をDBに書き込む記述 */
function customh1_save_postdata( $post_id ) {
	$change_h1 = $_POST['customh1'];
	if ( "" == get_post_meta( $post_id, 'customh1' )) {
		/* customh1というキーでデータが保存されていなかった場合、新しく保存 */
		add_post_meta( $post_id, 'customh1', $change_h1, true ) ;
	} else if ( $change_h1 != get_post_meta( $post_id, 'customh1' )) {
		/* customh1というキーのデータと、現在のデータが一致しなかった場合、更新 */
		update_post_meta( $post_id, 'customh1', $change_h1 ) ;
	} else if ( "" == $change_h1 ) {
		/* 現在のデータが無い場合、customh1というキーの値を削除 */
		delete_post_meta( $post_id, 'customh1' ) ;
	}
}

/* ４．上記関数の動作タイミング指定 */
add_action('admin_menu', 'customh1_add_custom_box'); /* 管理画面が開いたときに実行 */
add_action('save_post', 'customh1_save_postdata'); /* 更新ボタンが押されたときに実行 */


//==========================================================================
//  canonicalを特別に設定
//==========================================================================

/* 投稿画面 */

function add_canonical_box() {
	add_meta_box('canonical', 'canonical URL', 'canonical_setting', 'post', 'normal', 'high');
	add_meta_box('canonical', 'canonical URL', 'canonical_setting', 'page', 'normal', 'high');
}

function canonical_setting() {
	if (isset($_GET['post'])) {
		$page_canonical_array = get_post_meta( $_GET['post'], 'page_canonical');
		if (isset($page_canonical_array[0])) {
			$page_canonical = $page_canonical_array[0];
		} else {
			$page_canonical = "";
		}
	} else {
		$page_canonical = "";
	}

	$res = "<input type=\"text\" name=\"page_canonical\" value=\"".htmlspecialchars($page_canonical)."\" size=\"64\" maxlength=\"64\" />";
	echo $res;
}

function save_canonical_string($post_id) {
	if (isset($_POST['page_canonical'])) {
		$change_canonical = $_POST['page_canonical'];
		if (get_post_meta( $post_id, 'page_canonical') == "") {
			add_post_meta( $post_id, 'page_canonical', $change_canonical, true);
		} else {
			update_post_meta( $post_id, 'page_canonical', $change_canonical);
		}
	}
}

add_action('admin_menu', 'add_canonical_box');
add_action('save_post', 'save_canonical_string');

/* canonicalを表示 */

function canonical() {
	echo get_canonical();
}

function get_canonical() {

	$canonical = "";

	if(!is_home() && !is_front_page()) {
		$post_canonical_array = get_post_meta(get_the_ID(),'page_canonical');
		if (isset($post_canonical_array[0]) and ($post_canonical_array[0] != "")) {
			$canonical = '<link rel="canonical" href="'.$post_canonical_array[0]. '"/>'."\n";

			remove_action('wp_head', 'rel_canonical');
		}
	}
	return $canonical;
}


//==========================================================================
//  投稿画面にカスタムCSSを追加
//==========================================================================

add_action('admin_menu', 'custom_css_hooks');
add_action('save_post', 'save_custom_css');
add_action('wp_head','insert_custom_css');
function custom_css_hooks() {
	add_meta_box('custom_css', 'Custom CSS', 'custom_css_input', 'post', 'normal', 'high');
	add_meta_box('custom_css', 'Custom CSS', 'custom_css_input', 'page', 'normal', 'high');
}
function custom_css_input() {
	global $post;
	echo '<input type="hidden" name="custom_css_noncename" id="custom_css_noncename" value="'.wp_create_nonce('custom-css').'" />';
	echo '<textarea name="custom_css" id="custom_css" rows="5" cols="30" style="width:100%;">'.get_post_meta($post->ID,'_custom_css',true).'</textarea>';
}
function save_custom_css($post_id) {
	if (!wp_verify_nonce($_POST['custom_css_noncename'], 'custom-css')) return $post_id;
	if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return $post_id;
	$custom_css = $_POST['custom_css'];
	update_post_meta($post_id, '_custom_css', $custom_css);
}
function insert_custom_css() {
	if (is_page() || is_single()) {
		if (have_posts()) : while (have_posts()) : the_post();
			echo '<style type="text/css">'.get_post_meta(get_the_ID(), '_custom_css', true).'</style>';
		endwhile; endif;
		rewind_posts();
	}
}

//==========================================================================
//  カスタマイズ項目の追加と削除
//  http://wpdocs.sourceforge.jp/Theme_Customization_API
//  http://codex.wordpress.org/Plugin_API/Action_Reference/customize_register
//==========================================================================

function myd_customize_register($wp_customize){

	$wp_customize->remove_section('colors');

	$wp_customize->add_section('myd_options', array(
		'title'    => 'INFOPLATE MMC',
		'priority' => 120,
	));

	//  =============================
	//  ページの幅
	//  =============================
	$wp_customize->add_setting('myd_theme_options[page_width]', array(
		'capability' => 'edit_theme_options',
		'type'       => 'option',
	));

	$wp_customize->add_control('myd_options_page_width', array(
		'priority' => 1,
		'label'    => 'ページの幅',
		'section'  => 'myd_options',
		'settings' => 'myd_theme_options[page_width]',
	));


	//  =============================
	//  グローバルナビの幅
	//  =============================
	$wp_customize->add_setting('myd_theme_options[g-navi_width]', array(
		'capability' => 'edit_theme_options',
		'type'       => 'option',
	));

	$wp_customize->add_control('myd_options_g-navi_width', array(
		'priority'  => 2,
		'label'     => 'グローバルナビの幅',
		'section'   => 'myd_options',
		'settings'  => 'myd_theme_options[g-navi_width]',
		'type'      => 'select',
		'choices'   => array(
			'global-navi-width100' => 'ページ幅',
			'' => 'コンテンツ幅',
		),
	));


	//  =============================
	//  レイアウト
	//  =============================
	$wp_customize->add_setting('myd_theme_options[layout]', array(
		'default'    => '2カラム右サイドバー',
		'capability' => 'edit_theme_options',
		'type'       => 'option',
	));

	$wp_customize->add_control('myd_options_layout', array(
		'priority' => 3,
		'label'    => 'レイアウト',
		'section'  => 'myd_options',
		'settings' => 'myd_theme_options[layout]',
		'type'     => 'select',
		'choices'  => array(
			'c1'  => '1カラム',
			'c2r' => '2カラム右サイドバー',
			'c2l' => '2カラム左サイドバー',
			'c3'  => '3カラム',
			'c3r' => '3カラム右サイドバー',
		),
	));


	//  =============================
	//  メインカラー
	//  =============================
	$wp_customize->add_setting('myd_theme_options[main_color]', array(
		'default'    => '',
		'capability' => 'edit_theme_options',
		'type'       => 'option',
	));

	$wp_customize->add_control( new WP_Customize_Color_Control($wp_customize, 'main_color', array(
		'priority' => 4,
		'label'    => 'メインカラー',
		'section'  => 'myd_options',
		'settings' => 'myd_theme_options[main_color]',
	)));


	//  =============================
	//  サブカラー
	//  =============================
	$wp_customize->add_setting('myd_theme_options[sub_color]', array(
		'default'    => '',
		'capability' => 'edit_theme_options',
		'type'       => 'option',
	));

	$wp_customize->add_control( new WP_Customize_Color_Control($wp_customize, 'sub_color', array(
		'priority' => 5,
		'label'    => 'サブカラー',
		'section'  => 'myd_options',
		'settings' => 'myd_theme_options[sub_color]',
	)));


	//  =============================
	//  背景色
	//  =============================
	$wp_customize->add_setting('myd_theme_options[background_color]', array(
		'default'    => '',
		'capability' => 'edit_theme_options',
		'type'       => 'option',
	));

	$wp_customize->add_control( new WP_Customize_Color_Control($wp_customize, 'background_color', array(
		'priority' => 7,
		'label'    => '背景色',
		'section'  => 'myd_options',
		'settings' => 'myd_theme_options[background_color]',
	)));


	//  =============================
	//  リンク色
	//  =============================
	$wp_customize->add_setting('myd_theme_options[link_color]', array(
		'default'    => '',
		'capability' => 'edit_theme_options',
		'type'       => 'option',
	));

	$wp_customize->add_control( new WP_Customize_Color_Control($wp_customize, 'link_color', array(
		'priority' => 8,
		'label'    => 'リンク色',
		'section'  => 'myd_options',
		'settings' => 'myd_theme_options[link_color]',
	)));

}

add_action('customize_register', 'myd_customize_register');


//==========================================================================
//  ダッシュボードにスタイルシートを追加
//==========================================================================

function style_admin() {
	echo '<link rel="stylesheet" type="text/css" href="'.get_template_directory_uri().'/admin.css" />';
}
add_action('admin_head', 'style_admin');


// ウィジェット
require_once ( get_template_directory() . '/functions-widget.php' );

// ショートコード
require_once ( get_template_directory() . '/shortcodes/ip5_shortcodes_pro.php' );
require_once ( get_template_directory() . '/shortcodes/mce/ip5_shortcodes_tinymce_pro.php' );

// プロ限定機能
require_once ( get_template_directory() . '/functions-pro.php' );

// for Catch the web
require_once ( get_template_directory() . '/ctw/ctw_widget.php' );
require_once ( get_template_directory() . '/ctw/ctw_parts_tinymce.php' );

