チェ・ゲバムラの日記

脱犬の道を目指す男のブログ

【WordPress】良く使うfunctions.php管理画面やContactform7のバリデーション設定など(保存版)

WordPressで管理画面はAdvanced Custom Fieldsつかったりして本文欄いらないから消したり、
管理者と一般ユーザつくって一般からは投稿しかさせないとか、
一般Aと一般Bではお互いに投稿みれないとかメディアみれないとか、
とかく良く使うだろうってやつをメモしておく。
調べたら出てくるけどサイトをいくつか見るのもめんどいのでコピペ用。
変数とかは適当に変更した方が良いと思われる。

余談だけどContactForm7はすごい優秀なプラグインで良く使うけど、
バリデーション機能が中途半端だからこの設定とかしておかないとフォームデータとしては統一性が無いな。
(電話番号にハイフンがあるひとと無い人が混在したり)
てことでこれは個人的には保存版としたい。

<?php
/* アイキャッチ画像を表示 */
add_theme_support( 'post-thumbnails' );

add_action( 'init' , 'my_remove_post_editor_support' );

function my_remove_post_editor_support() {
remove_post_type_support( 'post', 'editor' );//投稿本文
remove_post_type_support( 'page', 'editor' );//固定ページ本文
remove_post_type_support( 'post', 'comments' ); // コメント
remove_post_type_support( 'post', 'revisions' ); // リビジョン
remove_post_type_support( 'post', 'page-attributes' ); // ページ属性
remove_post_type_support( 'post', 'excerpt' ); // 抜粋
remove_post_type_support( 'post', 'post-formats' ); // 投稿フォーマット
remove_post_type_support( 'post', 'trackbacks' ); // トラックバック
remove_post_type_support( 'post', 'custom-fields' ); // カスタムフィールド
remove_post_type_support( 'post', 'author' ); // 投稿作成者
remove_post_type_support( 'page', 'author' ); // 固定ページ作成者

unregister_taxonomy_for_object_type( 'post_tag', 'post' ); // タグ
}

/**
 * 投稿画面から不要な枠(メタボックス)を無効にします。
 */
function remove_post_meta_boxes() {
remove_meta_box( 'slugdiv', 'post', 'normal' ); // スラッグ
}
add_action( 'admin_menu', 'remove_post_meta_boxes' );

/**
 * 管理者以外は非表示にする項目を指定
 */
 function remove_menus () {
    if (!current_user_can('administrator')) {
      remove_menu_page( 'index.php' );                  // ダッシュボード
      //remove_menu_page( 'upload.php' );                 // メディア
      remove_menu_page( 'edit.php?post_type=page' );    // 固定ページ
      remove_menu_page( 'edit-comments.php' );          // コメント
      remove_menu_page( 'themes.php' );                 // 外観
      remove_menu_page( 'plugins.php' );                // プラグイン
      remove_menu_page( 'users.php' );                  // ユーザー
      remove_menu_page( 'tools.php' );                  // ツール
      remove_menu_page( 'options-general.php' );        // 設定
      remove_menu_page( 'profile.php' );        // プロフィ―ル
      remove_menu_page( 'edit.php?post_type=policy');
      remove_menu_page( 'edit.php?post_type=news');
      remove_menu_page( 'edit.php?post_type=movie');
      remove_menu_page( 'wpcf7'); //お問い合わせフォーム
      }
    }
    
add_action('admin_menu', 'remove_menus');

/**
 * バージョンアップ通知を管理者のみ表示させるようにします。
 */
function update_nag_admin_only() {
    if ( ! current_user_can( 'administrator' ) ) {
        remove_action( 'admin_notices', 'update_nag', 3 );
    }
}
add_action( 'admin_init', 'update_nag_admin_only' );


//ダッシュボードリダイレクト
add_action( 'admin_init', 'redirect_dashiboard' );
function redirect_dashiboard() {
        if ( '/wp/wp-admin/index.php' == $_SERVER['SCRIPT_NAME'] ) {
                wp_redirect( admin_url( 'edit.php' ) );
        }
}

/*
 * メディアの抽出条件にログインユーザーの絞り込み条件を追加する
 */
function display_only_self_uploaded_medias( $query ) {
if ( $user = wp_get_current_user() ) {
$query['author'] = $user->ID;
}
return $query;
}
add_action( 'ajax_query_attachments_args', 'display_only_self_uploaded_medias' );

/*-------------------------------------------*/
/* 投稿者の投稿(所有)のみにアクセス限定
/*-------------------------------------------*/
function show_owned_posts_only( $views ) {
    if (!current_user_can('administrator')) {
    unset($views['all']); // すべて
    unset($views['draft']); // 下書き
    unset($views['publish']); // 公開済み
    unset($views['pending']); // 保留中
    unset($views['trash']); // ゴミ箱
    }

    return $views;
}
add_filter('views_edit-post', 'show_owned_posts_only'); /* カスタム投稿の場合は>「edit-post」の「post」部分をカスタム投稿のスラッグに変更 */

/*-------------------------------------------*/
/* 投稿が0件でも他者の投稿一覧が見えないように
/*-------------------------------------------*/
function hide_other_posts($wp_query) {
    if (!current_user_can('administrator')) {
        global $current_screen, $current_user;

        if($current_screen->id != "edit-post") { /* カスタム投稿の場合は「-post>」の「post」部分をカスタム投稿のスラッグに変更 */
            return;
        }

        if(!$current_user->roles[0] == "author") { /* 対象とするユーザーグループ
を指定 */
            return false;
        }

        $wp_query->query_vars['author'] = $current_user->ID; /* 対象とするユーザ
ーグループを指定 */
    }
}
add_action('pre_get_posts', 'hide_other_posts');

/* 投稿タイプを追加 */
add_action( 'init', 'create_post_type' );
function create_post_type() {
        register_post_type( 'policy', //ポリシー投稿タイプ名を指定
                array(
                        'labels' => array(
                                'name' => __( 'ポリシー' ),
                                'all_items' => '投稿一覧',
                                'singular_name' => __( 'ポリシー' ),
                                'parent' => ''
                        ),
                        'public' => true,
                        'has_archive' => true, /* アーカイブページを持つ */
                        'menu_position' =>4, //管理画面のメニュー順位
                        'supports' => array( 'title', 'author' ),
                        'taxonomies' => array('policy_cat'),
                )
        );
        
        register_taxonomy(
                'policy_cat', /* タクソノミーの名前 */
                'policy', /* 使用するカスタム投稿タイプ名 */
                array(
                        'hierarchical' => true,
                        'update_count_callback' => '_update_post_term_count',
                        'label' => 'カテゴリー',
                        'singular_label' => 'カテゴリー',
                        'public' => true,
                        'show_ui' => true,
                        'publicly_queryable' => true,
                        'has_archive' => true,
                        'query_var' => true
                )
        );
};

//コンタクトフォームのメール確認用
add_filter( 'wpcf7_validate_email', 'wpcf7_text_validation_filter_extend', 11, 2 );
add_filter( 'wpcf7_validate_email*', 'wpcf7_text_validation_filter_extend', 11, 2 );

function wpcf7_text_validation_filter_extend( $result, $tag ) {
global $my_email_confirm;
$tag = new WPCF7_Shortcode( $tag );
$name = $tag->name;
$value = isset( $_POST[$name] )
? trim( wp_unslash( strtr( (string) $_POST[$name], "\n", " " ) ) )
: '';
if ($name == "your-email"){
$my_email_confirm=$value;
}
if ($name == "your-email_confirm" && $my_email_confirm != $value){
$result->invalidate( $tag,"確認用のメールアドレスが一致していません");
}
return $result;
}

/**
 * contact-form-7プラグインにて姓、名のフリガナが正しいかどうかを確認
 *
 */
add_filter('wpcf7_validate_text',  'wpcf7_validate_kana', 11, 2);
add_filter('wpcf7_validate_text*', 'wpcf7_validate_kana', 11, 2);
function wpcf7_validate_kana($result,$tag){

  $tag = new WPCF7_Shortcode($tag);
  $name = $tag->name;

  $value = isset($_POST[$name]) ? trim(wp_unslash(strtr((string) $_POST[$name], "\n", " "))) : "";

  // furiganaはフォーム側のnameです
  if ($name === "your-name-kana") {
     // ひらがな、全角と半角スペース許可
    if(!preg_match("/^[  \t\r\n]|[ぁ-ん]|[ー]+$/u", $value)) {

      $result->invalidate($tag, "全角ひらがなで入力してください。");
    }
  }
  return $result;
}

/**
 * contact-form-7プラグインにて年齢チェック
 */
add_filter('wpcf7_validate_text',  'wpcf7_validate_age', 11, 2);
add_filter('wpcf7_validate_text*', 'wpcf7_validate_age', 11, 2);
function wpcf7_validate_age($result,$tag){
  $tag = new WPCF7_Shortcode($tag);
  $name = $tag->name;
  $value = isset($_POST[$name]) ? trim(wp_unslash(strtr((string) $_POST[$name], "\n", " "))) : "";
  // フォーム側のnameです
  if ($name === "your-age") {
    //半角数字だが、18歳未満の場合エラー
    if((preg_match("/^[0-9]{1,4}$/", $value)) && $value < 18) {
        $result->invalidate($tag, "18歳未満の方は申込み不可です。");
    }
    //半角数字でない場合はエラー
    elseif(!preg_match("/^[0-9]{2,4}$/", $value)){
      $result->invalidate($tag, "半角数字で入力してください。");
    }
  }
  return $result;
}

/**
 * contact-form-7プラグインにて半角数字かどうかを確認 郵便番号
 */
add_filter('wpcf7_validate_text',  'wpcf7_validate_post', 11, 2);
add_filter('wpcf7_validate_text*', 'wpcf7_validate_post', 11, 2);
function wpcf7_validate_post($result,$tag){
  $tag = new WPCF7_Shortcode($tag);
  $name = $tag->name;
  $value = isset($_POST[$name]) ? trim(wp_unslash(strtr((string) $_POST[$name], "\n", " "))) : "";
  // フォーム側のnameです
  if ($name === "your-post") {
    // 半角数字のみ許可
    if(!preg_match("/^\d{3}\-\d{4}$/", $value)) {
      $result->invalidate($tag, "半角数字ハイフン付き(000-0000)で入力してくださ>い。");
    }
  }
  return $result;
}

/**
 * contact-form-7プラグインにて電話番号チェック
 */
add_filter('wpcf7_validate_tel',  'wpcf7_validate_tel', 11, 2);
add_filter('wpcf7_validate_tel*', 'wpcf7_validate_tel', 11, 2);
function wpcf7_validate_tel($result,$tag){
  $tag = new WPCF7_Shortcode($tag);
  $name = $tag->name;
  $value = isset($_POST[$name]) ? trim(wp_unslash(strtr((string) $_POST[$name], "\n", " "))) : "";
  // フォーム側のnameです
  if ($name === "your-tel") {
    // 半角数字のみ許可
    if(!preg_match("/^[0-9]{2,4}-[0-9]{2,4}-[0-9]{3,4}$/", $value)) {
      $result->invalidate($tag, "半角数字ハイフン付き(例:00-0000-0000)で入力し>てください。");
    }
  }
  return $result;
}

/* ログ出力
******************* */
if(!function_exists('_log')){
function _log($message) {
if (WP_DEBUG === true) {
if (is_array($message) || is_object($message)) {
error_log(print_r($message, true));
} else {
error_log($message);
}
}
}
}