<?php
/* 管理者ページをアクセス禁止に */
add_action( 'auth_redirect', 'subscriber_go_to_home' );
function subscriber_go_to_home( $user_id ) {
	$user = get_userdata( $user_id );
	if ( !$user->has_cap( 'edit_posts' ) ) {
		wp_redirect( get_home_url() );
		exit();
	}
}

/* ツールバー（admin bar）を非表示に */
add_action( 'after_setup_theme', 'subscriber_hide_admin_bar' );
function subscriber_hide_admin_bar() {
	$user = wp_get_current_user();
	if ( isset( $user->data ) && !$user->has_cap( 'edit_posts' ) ) {
		show_admin_bar( false );
	}
}

//ショートコードを使ったphpファイルの呼び出し方法
function my_php_Include($params = array()) {
	extract(shortcode_atts(array('file' => 'default'), $params));
	ob_start();
	get_template_part("/template-parts/$file");
//	include(STYLESHEETPATH . "/template-parts/$file.php");
	return ob_get_clean();
}
add_shortcode('gettemple', 'my_php_Include');


remove_filter ( 'the_content', 'wpautop' );		//<p>や<br>の保管を削除
remove_filter ( 'the_excerpt', 'wpautop' );		//<p>や<br>の保管を削除
remove_action('wp_head', 'wp_generator');		//header要素<meta name="generator" を削除
remove_action('wp_head', 'rel_canonical');		//header要素<link rel='canonical' を削除
remove_action('wp_head', 'wp_shortlink_wp_head');		//header要素<link rel='shortlink' を削除
remove_action('wp_head', 'wlwmanifest_link');		//header要素<link rel="wlwmanifest" を削除
remove_action('wp_head', 'rsd_link');		//header要素<link rel="EditURI" を削除


register_nav_menu('sidemenu', 'サイドメニュー');
add_filter('walker_nav_menu_start_el', 'description_in_nav_menu', 10, 4);
function description_in_nav_menu($item_output, $item){
	return preg_replace('/(<p.*?>[^<]*?)</', '$1' . "<li class=\"ca-sub\">{$item->description}</li></div><", $item_output);
}
register_nav_menu('footermenu', 'フッターメニュー');
register_nav_menu('spmenu', 'スマホダイアログメニュー');
//MW WP Formバリデーション設定----------------------------------------------------------------------------
/**
* my_error_message
* @param string $error
* @param string $key
* @param string $rule（半角小文字）
*/
function my_error_message( $error, $key, $rule ) {
if ( $key === 'kokyaku_id' && $rule === 'noempty' ) return '※お客様IDを入力してください';
if ( $key === 'kokyaku_mei' && $rule === 'noempty' ) return '※お客様名を入力してください';
if ( $key === 'bottle' && $rule === 'noempty' ) return '※注文ボトル本数を入力してください';
if ( $key === 'haitatsu_day' && $rule === 'noempty' ) return '※配達希望日を入力してください';
if ( $key === 'time' && $rule === 'noempty' ) return '※配達希望時間を入力して下さい';
if ( $key === 'time' && $rule === 'date' ) return '※日付の形式ではありません';

return $error;
}
add_filter( 'mwform_error_message_mw-wp-form-23', 'my_error_message', 10, 3 );


if ( ! function_exists( 'twentyfourteen_paging_nav' ) ) :
/**
 * ページナビ（カテゴリページでの1ページ当たりの表示数を超えた場合の遷移関数）
 * Display navigation to next/previous set of posts when applicable.
 *
 * @since Twenty Fourteen 1.0
 *
 * @global WP_Query   $wp_query   WordPress Query object.
 * @global WP_Rewrite $wp_rewrite WordPress Rewrite object.
 */
function twentyfourteen_paging_nav() {
	global $wp_query, $wp_rewrite;

	// Don't print empty markup if there's only one page.
	if ( $wp_query->max_num_pages < 2 ) {
		return;
	}

	$paged        = get_query_var( 'paged' ) ? intval( get_query_var( 'paged' ) ) : 1;
	$pagenum_link = html_entity_decode( get_pagenum_link() );
	$query_args   = array();
	$url_parts    = explode( '?', $pagenum_link );

	if ( isset( $url_parts[1] ) ) {
		wp_parse_str( $url_parts[1], $query_args );
	}

	$pagenum_link = remove_query_arg( array_keys( $query_args ), $pagenum_link );
	$pagenum_link = trailingslashit( $pagenum_link ) . '%_%';

	$format  = $wp_rewrite->using_index_permalinks() && ! strpos( $pagenum_link, 'index.php' ) ? 'index.php/' : '';
	$format .= $wp_rewrite->using_permalinks() ? user_trailingslashit( $wp_rewrite->pagination_base . '/%#%', 'paged' ) : '?paged=%#%';

	// Set up paginated links.
	$links = paginate_links( array(
		'base'     => $pagenum_link,
		'format'   => $format,
		'total'    => $wp_query->max_num_pages,
		'current'  => $paged,
		'mid_size' => 2,
		'add_args' => array_map( 'urlencode', $query_args ),
		'prev_text' => __( '&larr; 前へ', 'twentyfourteen' ),
		'next_text' => __( '次へ &rarr;', 'twentyfourteen' ),
	) );

	if ( $links ) :

	?>
	<nav class="navigation paging-navigation" role="navigation">
		<div class="pagination loop-pagination clearfix">
			<?php echo $links; ?>
		</div><!-- .pagination -->
	</nav><!-- .navigation -->
	<?php
	endif;
}
endif;

#1ページの表示件数を100件にするコードです。
add_action( 'pre_get_posts', 'mypaging' );
function mypaging($query) {
    if ( is_admin() || ! $query->is_main_query() ) { // 管理画面を表示している場合を除外。またメインループでない場合を除外
        return;
    }
    $query->set('posts_per_page',100);
}

#1ページの表示の順番を古い順に表示する。
function my_pre_get_posts($query) {
    if (is_category('job') || is_category('service') || is_category('academic') || is_category('sale') || is_category('food-drink') || is_category('free-trial')) {
        $query->set('order', 'ASC');
    }
}
add_action('pre_get_posts', 'my_pre_get_posts');


// ウィジェット
register_sidebar(array(
	'name' => 'サイドバーウィジェットエリア（上）',
	'id' => 'primary-widget-area',
	'description' => 'サイドバー上部のウィジェットエリア',
	'before_widget' => '<aside id="%1$s" class="widget-container %2$s">',
	'after_widget' => '</aside>',
	'before_title' => '<h1 class="widget-title">',
	'after_title' => '</h1>',
));
register_sidebar(array(
	'name' => 'サイドバーウィジェットエリア（下）',
	'id' => 'secondary-widget-area',
	'description' => 'サイドバー下部のウィジェットエリア',
	'before_widget' => '<aside id="%1$s" class="widget-container %2$s">',
	'after_widget' => '</aside>',
	'before_title' => '<h1 class="widget-title">',
	'after_title' => '</h1>',
));

/* 管理者以外が新規投稿などのページを開いたらカテゴリの最初の項目に自動チェック */
add_action('admin_print_footer_scripts', 'admin_print_footer_scripts_custom', 21);
function admin_print_footer_scripts_custom()
{
  $user_roles = wp_get_current_user()->roles;
  if (!in_array('administrator', $user_roles)) {
    echo '<script type="text/javascript">
    //<![CDATA[
    jQuery(document).ready(function($){
      // default check
      if ($("#category-all .categorychecklist input[type=checkbox]:checked").length == 0) {
        $("#category-all .categorychecklist li:first-child input:first-child").attr("checked", "checked");
      }
    });
    //]]>
    </script>';
  }
}

/* 管理者権限以外で投稿した場合のタグが削除される問題を解決 */
function my_wp_kses_allowed_html( $tags, $context ) {
  if ( $context === 'post' ) {
	$tags['script']['type'] = true;
	$tags['br'] = true;
  }
  return $tags;
}
add_filter( 'wp_kses_allowed_html', 'my_wp_kses_allowed_html', 10, 2 );


/* 記事公開時に指定のアドレスにメール通知を送信 */
add_action( 'transition_post_status', function( $new_status, $old_status, $post ) {
  if ( 'publish' == $new_status  &&  'publish' != $old_status && 'post' == $post->post_type ) {
    $header = array( 'From: kanrimaster@mukauno-sato.com' );
    wp_mail( 'tomohiro.yamaguchi@mukauno-sato.com', $post->post_title, get_permalink( $post->ID ), $header );
  }
}, 10, 3 );


// アイキャッチ画像を利用できるようにします。
add_theme_support('post-thumbnails');

// アイキャッチ画像サイズ設定
set_post_thumbnail_size(90,90,true);

// サイドバー用画像サイズ設定
add_image_size('small_thumbnail',61,61,true);

// アーカイブ用画像サイズ設定
add_image_size('large_thumbnail',250,250,true);

// サブページヘッダー用画像サイズ設定
add_image_size('category_image',658,113,true);

// モールイメージ用画像サイズ設定
add_image_size('pickup_thumbnail',302,123,true);

//　一覧記事取得関数 --------------------------------------------------------------------------------
// "num" = 表示記事数, "cat" = カテゴリ番号
// 呼び出し元での指定も可能 -> [getCategoryArticle num="x" cat="y"]
function getCatItems($atts, $content = null) {
	extract(shortcode_atts(array(
	  "num" => '200',
	  "cat" => '2'
	), $atts));
	
	// 処理中のpost変数をoldpost変数に退避
	global $post;
	$oldpost = $post;
	
	// カテゴリーの記事データ取得
	$myposts = get_posts('numberposts='.$num.'&order=DESC&orderby=post_date&category='.$cat);
	
	if($myposts) {
		// 記事がある場合↓
		$retHtml = '<ul>';
		// 取得した記事の個数分繰り返す
		foreach($myposts as $post) :
 
			// 記事オブジェクトの整形
			setup_postdata($post);
 			
			// 文章のみのエリアをliで囲う
			$retHtml .= '<li>';
			
			$cat = get_the_category(); // 表示中の記事のカテゴリ（配列）
			$cat_name = $cat[0]->category_nicename;
			$parent_cat = get_category($cat[0]->parent); // 親カテゴリのIDを取得

			// タイトル設定(リンクも設定する)
			$retHtml.= '<figure>';
			$retHtml.= '<a href="' . get_permalink() . '">' ;
			$retHtml.= '<img src="' . home_url('/') .'img/works/'. $parent_cat->slug .'/'. $cat_name . '/' . get_post_field('post_name',get_the_ID()) . '/001.jpg' . '"></a>';
			$retHtml.= '<figcaption">' . get_the_title();	
			$retHtml.= '</figcaption">';
			$retHtml.= '</figure">';
			$retHtml.= '<p class="more">';
			$retHtml.= '<a href="' . home_url('/') .'img/works/'. $parent_cat->slug .'/'. $cat_name . '/' . get_post_field('post_name',get_the_ID()) . '">';
			$retHtml.= 'more';
			$retHtml.= '</a>';
			$retHtml.= '</p>';
			$retHtml.= '</li>';

		endforeach;
		
		$retHtml.= '</ul>';
	} else {
		// 記事がない場合↓
		$retHtml='<p>記事がありません。</p>';
	}
	
	// oldpost変数をpost変数に戻す
	$post = $oldpost;
	
	return $retHtml;
}
// 呼び出しの指定
add_shortcode("getCategoryArticle", "getCatItems");

/* 投稿者アーカイブを無効化してWordPressのユーザ名を隠す */
add_filter( 'author_rewrite_rules', '__return_empty_array' );
function disable_author_archive() {
if( $_GET['author'] || preg_match('#/author/.+#', $_SERVER['REQUEST_URI']) ){
wp_redirect( home_url( '/404.php' ) );
exit;
}
}
add_action('init', 'disable_author_archive');

?>