2. 8. 3 投稿作成のカスタマイズ(3)保存

自動保存防止, スラッグ設定, 更新日, テンプレート, サブタイトル等

自動保存防止

 投稿作成時に自動で次のものが作成されます。
  ・一定時間間隔での自動保存版(下書の場合は更新)
  ・新規作成時、タイトル入力時の自動下書保存
  ・リビジョン
  ・プレビュー時の自動保存版(下書の場合は更新)
 特に、下書の場合、ユーザーの意思とは無関係に更新されます。
 また、自動保存版や、リビジョンの復元方法は一般ユーザーに使い勝手が良いとはいえません。カスタムフィールドは復元されません。
 そのため、これらの自動保存等を防止します。
 自動保存の時間間隔を広げれば、一定時間間隔での自動保存は実質的に防止できます。
 リビジョンはwp-config.phpファイルの設定でも無効化できます。ただし、すべてのリビジョンを無効化するものではありません。
 JavaScriptの自動保存は、DOING_AUTOSAVE で判定できるようです。
 プレビュー時の自動保存版(下書を除く)は、リビジョンと判定されます。
 なお、自動保存の防止でエラーメッセージが表示されます。スタイルシートでこのメッセージを非表示にする必要があります。

コード

// --------------------------------
// 自動保存防止
//   “カラ”と判定
// --------------------------------
function hk_functions_insert_post_empty_content( $maybe_empty, $postarr ) {
    // 自動保存
    if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )    return true;
    // リビジョン
    $post_id = $postarr['ID'];
    if ( ! empty( $post_id ) ) {
        if ( wp_is_post_revision( $post_id ) )            return true;
    }
    // プレビュー
    if (( isset( $_POST['wp-preview'] ) ) && ( $_POST['wp-preview'] == 'dopreview' ))
        return true;
    return $maybe_empty;
}
add_filter( 'wp_insert_post_empty_content', 'hk_functions_insert_post_empty_content', 10, 2 );

前処理

 次の処理を行います。
   ・タイトル先頭の半角スペース保護
   ・スラッグ設定
   ・更新日の操作
   ・序文処理・テンプレート処理
   ・フック設定
(1)タイトル先頭の半角スペース保護
 投稿を保存する際に、タイトル先頭の半角スペースが削除されます。タイトル先頭の半角スペースを保護します。タイトル順に投稿を並べる場合に役立ちます。
 タイトル先頭の半角スペースが削除されのは、次のデフォルトフィルターが原因のようです。
   add_filter( 'title_save_pre', 'trim' );
 このフィルターを削除しても保護できそうですが、タイトルがスラッグの設定に使用されています。今後も大丈夫かどうか確証がありません。
 $_REQUEST['post_title'] に入力したタイトルが残っているのでこれを使ってタイトルを復元しています。
(2)スラッグ設定
 投稿を作成する際、よく忘れるのが、スラッグの設定です。設定を忘れるとスラッグが日本語になります。なお、draft の場合、自動設定されないようです。
 寄稿者で、post_status が pending(承認待ち)の場合、スラッグが削除されます。
 このため、スラッグを自動設定します。
 自作のカテゴリメタボックス(HK版)を使用している場合、カテゴリを1つに限定しているので、投稿の場合には、カテゴリスラッグに投稿IDを付加しています。使用していない場合、'post-'に投稿IDを付加しています。
 固定ページの場合、'page-'に投稿IDを付加しています。
 $_REQUEST['post_name'] のチェックは、スラッグメタボックスが組み込まれていない場合への対処です。
 スラッグメタボックスを組み込んでいて、スラッグ入力が無い場合、通常の自動設定。
 スラッグメタボックスを組み込んでいて、スラッグ入力が有り、承認待ちの場合、入力されたスラッグで設定。
 スラッグメタボックスを組み込んでなく、承認待ちの場合、更新前のスラッグで復元。
(3)更新日の操作
 更新前のデータを利用しています。
(4)序文処理・テンプレート処理
 “序文”というタイトルで作成された投稿は、そのカテゴリアーカイブの序文としてテーマの中で使用しています。
 “テンプレート”というタイトルで作成された投稿は、そのカテゴリの投稿のテンプレートとして使用しています。
(5)フック設定
 フックを設定しています。このフックは自作の他のプラグインで利用しています。

 “投稿データチェック”では、あらかじめ自動保存を防止しているため、自動保存の除外は行っていません。

コード

// --------------------------------
// 前処理
//   タイトル先頭の半角スペース保護
//   スラッグ設定
//   更新日の操作
//   序文処理・テンプレート処理
//   フック設定
// --------------------------------
function hk_functions_insert_post_data( $data, $postarr ) {
    // post_id
    $post_id = $postarr['ID'];
    if ( empty( $post_id ) )                            return $data;
    // 投稿データチェック
    $post_type   = $data['post_type'];
    $post_status = $data['post_status'];
    $rtc = hk_functions_check_insert_post( $post_type, $post_status );
    if ( ! $rtc )                                       return $data;
    // 更新前データ取得
    $old_post = get_post( $post_id );
    // タイトル先頭の半角スペース保護
    if ( $post_type == 'post' ) {
        if ( isset( $_REQUEST['post_title'] ) ) {
            $post_title = $_REQUEST['post_title'];
            $post_title = rtrim( $post_title );
            if ( $post_title != '' )
                $data['post_title'] = $post_title;
        }
    }
    // スラッグ設定
    if (( $post_type == 'post' ) || ( $post_type == 'page' )) {
        // スラッグメタボックス有り
        if ( isset( $_REQUEST['post_name'] ) ) {
            $post_name = $_REQUEST['post_name'];
            // スラッグ入力無し → 自動設定
            if ( $post_name == '' ) {
                if ( $post_type == 'post' ) {
                    // カテゴリメタボックス(HK版)ID取り込み
                    $cat_id = hk_func_post_read( 'hk_cat_div', 1 );
                    // カテゴリメタボックス(HK版)無し
                    if ( $cat_id == '' )
                        $data['post_name'] = 'post-'.$post_id;
                    // カテゴリメタボックス(HK版)有り
                    else {
                        $cat_obj  = get_category( $cat_id );
                        $cat_slug = $cat_obj->slug;
                        $data['post_name'] = $cat_slug.'-'.$post_id;
                    }
                }
                else
                    $data['post_name'] = 'page-'.$post_id;
            }
            // スラッグ入力有の場合
            else {
                // 寄稿者承認待ち → スラッグ設定
                if (( $data['post_status'] == 'pending' ) && ( ! current_user_can( 'publish_posts' ) )) {
                    $post_name = sanitize_title( $post_name );
                    $data['post_name'] = $post_name;
                }
            }
        }
        // スラッグメタボックス無し=スラッグ設定済み
        else {
            // 寄稿者承認待ち → スラッグ復元
            if (( $data['post_status'] == 'pending' ) && ( ! current_user_can( 'publish_posts' ) ))
                $data['post_name'] = $old_post->post_name;
        }
    }
    // 更新日の操作
    if (( $post_type == 'post' ) || ( $post_type == 'page' )) {
        // 作成日と同じにする
        if ( hk_func_post_read( 'hk_post_modified_1', 1 ) == 'yes' ) {
            $data['post_modified']     = $old_post->post_date;
            $data['post_modified_gmt'] = $old_post->post_date_gmt;
        }
        // 更新日を変更しない
        if ( hk_func_post_read( 'hk_post_modified_2', 1 ) == 'yes' ) {
            $data['post_modified']     = $old_post->post_modified;
            $data['post_modified_gmt'] = $old_post->post_modified_gmt;
        }
    }
    // 序文
    if ( $post_type == 'post' ) {
        $old_post_title = '';
        if ( isset( $old_post->post_title ) )
            $old_post_title = $old_post->post_title;
        $new_post_title = $data['post_title'];
        // タイトルチェック
        if (( $old_post_title == '序文' ) || ( $new_post_title == '序文' )) {
            // タイトル 固定
            $data['post_title'] = '序文';
            // post_status 設定
            if ( $data['post_status'] != 'draft' )
                $data['post_status'] = 'private';
        }
    }
    // テンプレート
    if ( $post_type == 'post' ) {
        if (( $old_post_title == 'テンプレート' ) || ( $new_post_title == 'テンプレート' )) {
            // タイトル 固定
            $data['post_title'] = 'テンプレート';
            // post_status 設定
            if ( $data['post_status'] != 'draft' )
                $data['post_status'] = 'private';
        }
    }
    // フック設定
    $data = apply_filters( 'hk_func_insert_post_data', $data, $post_id, $old_post );
    return $data;
}
add_filter( 'wp_insert_post_data', 'hk_functions_insert_post_data', 10, 2 );

// --- サブルーチン ---------------
// 投稿データチェック
//   除外:ゴミ箱への移動
//         投稿・固定ページ・カスタム投稿以外
//   戻り値:true :非除外
//           false:除外
// --------------------------------
function hk_functions_check_insert_post( $post_type, $post_status ) {
    // ゴミ箱への移動の除外
    if ( isset( $_REQUEST['action'] ) ) {
        if ( $_REQUEST['action'] == 'trash' )          return false;
        if ( $_REQUEST['action'] == 'untrash' )        return false;
    }
    // ユーザー削除時のゴミ箱への移動の除外
    if ( $post_status == 'trash' )                     return false;
    // post_type post、page、hk_temp 以外を除外
    if (( $post_type != 'post' )
     && ( $post_type != 'page' )
     && ( $post_type != 'hk_temp' ))                   return false;
    return true;
}

後処理

 次の処理を行います。
   ・サブタイトル保存
   ・カテゴリ保存
   ・開催日・終了日・添付ファイル保存
   ・フック設定
(1)サブタイトル保存
 カスタムフィールドに保存します。
(2)カテゴリ保存
 自作のカテゴリメタボックス(HK版)のデータを取り込み、投稿のカテゴリをひとつに限定して保存します。
(3)開催日・終了日・添付ファイル保存
 開催日メタボックスのデータを取り込み保存します。、
 開催日、終了日、ファイル名称は、カスタムフィールドに次の名称で保存しています。
  ・開催日:'01_開催日'
  ・終了日:'01_終了日'
  ・ファイル名称:'01_添付ファイル'
 アップロードしたファイルは、カテゴリ毎に次のディレクトリに保存しています。
  WP_CONTENT_DIR.'/uploads/category/カテゴリスラッグ/
(4)フック設定
 フックを設定しています。このフックは自作の他のプラグインで利用しています。

コード

// --------------------------------
// 後処理
//   サブタイトル保存
//   カテゴリ保存
//   開催日・終了日・添付ファイル保存
//   フック設定
// --------------------------------
function hk_functions_save_post( $post_id, $post ) {
    // post_id
    if ( empty( $post_id ) )                                return;
    // 投稿データチェック
    $post_type   = $post->post_type;
    $post_status = $post->post_status;
    $rtc = hk_functions_check_insert_post( $post_type, $post_status );
    if ( ! $rtc )                                           return;
    // サブタイトル保存・削除
    $sub_title = hk_func_post_read( 'hk_sub_title', 1 );
    if ( $sub_title != '' )
        update_post_meta( $post_id, 'sub_title', $sub_title );
    else
        delete_post_meta( $post_id, 'sub_title' );
    // カテゴリ保存
    $cat_id = hk_func_post_read( 'hk_cat_div', 1 );
    if ( $cat_id != '' )
        wp_set_post_categories( $post_id, array( $cat_id ), false );
    // 開催日・終了日・添付ファイル保存
    hk_functions_save_event_date( $post_id, $post );
    // フック設定
    do_action( 'hk_func_save_post', $post_id, $post );
    return;
}
add_action( 'save_post', 'hk_functions_save_post', 10, 2 );

// --- サブルーチン ---------------
// 開催日・終了日・添付ファイル保存
// --------------------------------
function hk_functions_save_event_date( $post_id, $post ) {
    $post_type = $post->post_type;
    // 開催日・終了日・添付ファイル
    $cat_type = '';
    if ( $post_type == 'post' ) {
        // 序文、テンプレートを除外
        $post_title = $post->post_title;
        if (( $post_title != '序文' ) && ( $post_title != 'テンプレート' )) {
            // カテゴリタイプ
            $cats = get_the_category( $post_id );
            if ( $cats ) {
                $cat_id   = $cats[0]->cat_ID;
                $cat_type = hk_func_get_cat_type( $cat_id );
            }
        }
    }
    if ( $cat_type == 'date' ) {
        // cat_slug
        $cat_slug = $cats[0]->slug;
        // 開催日取り込み
        $year  = hk_func_post_read( 'hk_event_year',  1 );
        $month = hk_func_post_read( 'hk_event_month', 1 );
        $day   = hk_func_post_read( 'hk_event_day',   1 );
        $ymd_open = '';
        // カスタムフィールドデータ保存・削除
        if ( ($year == '') || ($month == '') || ($day == '') )
            delete_post_meta( $post_id, '01_開催日' );
        else {
            $ymd_open = $year.'-'.$month.'-'.$day;
            update_post_meta( $post_id, '01_開催日', $ymd_open );
        }
        // 終了日取り込み
        $year  = hk_func_post_read( 'hk_event_end_year',  1 );
        $month = hk_func_post_read( 'hk_event_end_month', 1 );
        $day   = hk_func_post_read( 'hk_event_end_day',   1 );
        // カスタムフィールドデータ保存・削除
        if ( ($year == '') || ($month == '') || ($day == '') ) {
            if ( $ymd_open == '' )
                delete_post_meta( $post_id, '01_終了日' );
            else {
                $ymd_end = $ymd_open;
                update_post_meta( $post_id, '01_終了日', $ymd_end );
            }
        }
        else {
            $ymd_end = $year.'-'.$month.'-'.$day;
            update_post_meta( $post_id, '01_終了日', $ymd_end );
        }
        // 添付ファイル
        $file = get_post_meta( $post_id, '01_添付ファイル', true );
        // 既アップロードファイル削除
        $file_del = hk_func_post_read( 'hk_event_file_del', 1 );
        if ( $file_del == 'yes' ) {
            // 拡張子
            $pos1 = strrpos( $file, '.' );
            $file_ext = substr( $file, $pos1 );
            // ファイル名
            $filename = $cat_slug.'-'.$post_id.$file_ext;
            $filename = WP_CONTENT_DIR.'/uploads/category/'.$cat_slug.'/'.$filename;
            unlink( $filename );
            $file = '';
        }
        // アップロード
        if (( isset( $_FILES['hk_event_file']['tmp_name'] ) )
         && ( is_uploaded_file( $_FILES['hk_event_file']['tmp_name'] ) )) {
            // アップロードルートディレクトリ
            $dir = WP_CONTENT_DIR.'/uploads/category';
            if ( ! file_exists( $dir ) ) {
                umask( 0 );
                mkdir( $dir );
            }
            // アップロードディレクトリ
            $dir .= '/'.$cat_slug;
            if ( ! file_exists( $dir ) ) {
                umask( 0 );
                mkdir( $dir );
            }
            // アップロードファイル名
            $file = $_FILES['hk_event_file']['name'];
            $file = mb_convert_encoding( $file, "UTF-8", "auto" );
            // 拡張子
            $pos1 = strrpos( $file, '.' );
            if ( $pos1 !== false ) {
                $file_ext = substr( $file, $pos1 );
                // 保存ファイル名
                $filename = $cat_slug.'-'.$post_id.$file_ext;
                $filename = $dir.'/'.$filename;
                // ファイルアップロード実行
                if ( move_uploaded_file( $_FILES['hk_event_file']['tmp_name'], $filename ) )
                    chmod( $filename, 0666 );
                else    $file = '';
            }
            else    $file = '';
        }
        // カスタムフィールドデータ保存・削除
        if ( $file != '' )
            update_post_meta( $post_id, '01_添付ファイル', $file );
        else
            delete_post_meta( $post_id, '01_添付ファイル' );
    }
    return;
}

 次の関数は、“共通関数”に記載します。
   hk_func_post_read
   hk_func_get_cat_type

 このプログラムをお使いになる場合は、お使いになる方の自己責任でお願いします。

関連

更新日:2016/03/22
掲載日:2016/03/22