【WordPress】管理画面をカスタム

最近、仕事でワードプレスを使用し、管理画面をカスタムする事が多々あり、
だんだん、おもちゃ感覚になってきたのでメモ


ちなみに環境は、WP4.4.1 / CentOS6.x / httpd2.x / php5.4.x



「エラーメッセージ」について

管理画面で任意のエラーメッセージを表示したい事ってありますよね?

↓こんなやつとか(正常系メッセージ)↓






ファイル名: /wp-content/plugins/sample_plugin.php


class ClassName
{
// コンストラクタ
public function __construct()
{
add_action( 'wp_insert_post_data'  , array( $this , 'sample_method' )  , 10, 2 ); 
add_action( 'admin_notices'          , array( $this , 'admin_notices'   ) , 10, 2 ); 
}

// エラー発生
function sample_method( ) 
{
~何かの処理~

$e = new WP_Error();
$e->add( 'error', __( 'この投稿はエラーです。', 'custom-admin' ) ); 
set_transient( 'custom-admin-errors' , $e->get_error_messages(), 10 );

// エラーメッセージではなく、エラー画面を表示する場合は、下記コメントアウト解除
//wp_die($e, null, array('response' => 403, 'back_link' => true)); 
}

  // アラート表示
function admin_notices()
{
?>
    <?php if ( $messages = get_transient( 'custom-admin-errors' ) ): ?>
    <div class="error">
        <ul>
            <?php foreach( $messages as $message ): ?>
                <li><?php echo esc_html($message); ?>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>
<?php
}
}

コメント