カスタムフィールドだけではなく、他のところでも使用可能です。
1つの方法で、ほかにもやり方があります。
まとめ
/**
* カスタムフィールド保存
*
* @param int $post_id 投稿やページのID
*/
function save_page_meta_box( $post_id ) {
$keys = array(
'nav',
'title',
'image',
);
if ( isset( $_POST['nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), basename( __FILE__ ) ) ) {
// サニタイズ処理.
$post_sanitize = array();
foreach ( $keys as $key ) {
if ( isset( $_POST[ $key ] ) ) {
$post_sanitize[ $key ] = sanitize_text_field( wp_unslash( $_POST[ $key ] ) );
}
}
} else {
return $post_id;
}
// パーミッションを書く(エディターさんは保存NGなど)
// 保存の処理
foreach ( $keys as $key ) {
// 古い情報を取得
$old = get_post_meta( $post_id, _key, true );
// POSTされた値があるなら、$newに入れる
if ( isset( $post_sanitize[ $key ] ) ) {
$new = $post_sanitize[ $key ];
} else {
$new = '';
}
// 古い情報とPOSTされた値を比較して、保存or削除
if ( $new && $new !== $old ) {
update_post_meta( $post_id, $cf_key, $new );
} elseif ( '' === $new && $old ) {
delete_post_meta( $post_id, $cf_key, $old );
}
}
}
add_action( 'save_post', 'save_page_meta_box' );
その2
こっちでもいいけど、ダメな場合もあり注意!
/**
* カスタムフィールド保存
*
* @param int $post_id 投稿やページのID
*/
function save_page_meta_box( $post_id ) {
if ( isset( $_POST['nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), basename( __FILE__ ) ) ) {
// サニタイズ処理.
$post_sanitize = array();
foreach ( $_POST as $key => $val ) {
$post_sanitize[ $key ] = wp_kses_post( wp_unslash( $val ) );
}
} else {
return $post_id;
}
// パーミッションを書く(エディターさんは保存NGなど)
// 保存するキーの配列
$keys = array(
'nav',
'title',
'image',
);
// 保存の処理
foreach ( $keys as $key ) {
// 古い情報を取得
$old = get_post_meta( $post_id, _key, true );
// POSTされた値があるなら、$newに入れる
if ( isset( $post_sanitize[ $key ] ) ) {
$new = $post_sanitize[ $key ];
} else {
$new = '';
}
// 古い情報とPOSTされた値を比較して、保存or削除
if ( $new && $new !== $old ) {
update_post_meta( $post_id, $cf_key, $new );
} elseif ( '' === $new && $old ) {
delete_post_meta( $post_id, $cf_key, $old );
}
}
}
add_action( 'save_post', 'save_page_meta_box' );
内容
$POSTで送られてくる内容を定義
$keys = array( 'nav', 'title', 'image', );
ノンスチェックとサニタイズ処理
if ( isset( $_POST['nonce'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), basename( __FILE__ ) ) ) {
// サニタイズ処理.
$post_sanitize = array();
foreach ( $keys as $key ) {
if ( isset( $_POST[ $key ] ) ) {
$post_sanitize[ $key ] = sanitize_text_field( wp_unslash( $_POST[ $key ] ) );
}
}
} else {
return $post_id;
}
basename( __FILE__ ) は、パスの最後にある名前の部分を返すphp関数

PHP: basename - Manual
パスの最後にある名前の部分を返す
__FILE__ はphpのマジック変数
ファイルのフルパスとファイル名 (シンボリックリンクを解決した後のもの)。 インクルードされるファイルの中で使用された場合、インクルードされるファイルの名前が返されます。

PHP: マジック定数 - Manual
マジック定数
return は関数(function)を終了させる。

PHP: return - Manual
return
その2の場合
すべての%_POSTをノンスチェックとサニタイズ処理しているだけの違いのハズだけど、うまくいかないときもある。
使わないのがいいかも。
ちなみに入力部分のノンス
echo '<input type="hidden" name="nonce" value="' . esc_attr( wp_create_nonce( basename( __FILE__ ) ) ) . '">';
とノンスを出力しています。


