Skip to content

Instantly share code, notes, and snippets.

@fumikito
Created October 15, 2025 04:27
Show Gist options
  • Save fumikito/d0db7624b8de09b9b508f26e572cc339 to your computer and use it in GitHub Desktop.
Save fumikito/d0db7624b8de09b9b508f26e572cc339 to your computer and use it in GitHub Desktop.
Chrome Dev ToolsのMCPサーバーがWordPressにログインできるようにするmu-plugins
<?php
/**
* Plugin Name: Local WordPress Login
* Description: Force current user with specified user_login
* Version: 1.0.0
* Author: Takahshi_Fumiki
* License: GPL 2.0 or later
* Installation: wp-content/mu-pluginsにこのファイルを配置し、
* wp-config.phpに定数 LOCAL_LOGGED_IN_AS を定義。
* e.g.
* define( 'LOCAL_LOGGED_IN_AS', 'admin' );
*/
/**
* 現在のユーザーを上書きする
*/
add_filter( 'determine_current_user', function( $user_id ) {
if ( 'local' !== wp_get_environment_type() ) {
// ローカル専用
return $user_id;
}
// LOCAL_LOGGED_IN_AS 定数がなければなにもしない。
if ( ! defined( 'LOCAL_LOGGED_IN_AS' ) || empty( LOCAL_LOGGED_IN_AS ) ) {
return $user_id;
}
// 指定されたユーザーを取得
$user = get_user_by( 'login', LOCAL_LOGGED_IN_AS );
if ( ! $user ) {
return $user_id;
}
// 既に同じユーザーIDが設定されている場合は何もしない。同一セッションでの実行を考慮。
if ( $user_id && (int) $user_id === (int) $user->ID ) {
return $user_id;
}
// 念のためCookieも発行してみる(これが現状で動かない部分)
wp_set_current_user( $user->ID, $user->user_login );
wp_set_auth_cookie( $user->ID, true );
// ログインしているとされるユーザーのIDを返す
return $user->ID;
}, 30 );
/**
* auth_redirect() のオーバーライド
*
* Chrome DevTools MCPのようにクッキーを保持できない環境で、
* wp-adminにアクセスできるようにする。
* auth_redirectの中でwp_validate_auth_cookie()が走ってしまうため。
*
* ローカル環境でのみ動作。
*/
if ( ! function_exists( 'auth_redirect' ) && 'local' === wp_get_environment_type() ) {
function auth_redirect() {
// ログイン済みなら認証OK
if ( get_current_user_id() ) {
return;
}
// 未ログインならログインページへリダイレクト
nocache_headers();
$redirect = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
$login_url = wp_login_url( $redirect, true );
wp_redirect( $login_url );
exit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment