我不建议检测它是否不是admin或REST API,因为使用这种方法,您还需要检测它是否不是a WP-Cron job, an AJAX request, 或the login screen.
我认为最好直接测试前端wp_using_themes()
. 需要注意的是,您仍然需要确保它不是REST API请求,for reasons.
if ( wp_using_themes() && ! _tmp_is_rest_api_request() ) {
wp_die( \'i will only run on the front end\' );
}
/**
* Returns true if the current request is for the REST API.
*
* @todo: Replace this once Core provides a canonical way to do this: https://core.trac.wordpress.org/ticket/42061.
*
* @return bool
*/
function _tmp_is_rest_api_request() {
if ( empty( $_SERVER[\'REQUEST_URI\'] ) ) {
return false;
}
$rest_prefix = trailingslashit( rest_get_url_prefix() );
return false !== strpos( $_SERVER[\'REQUEST_URI\'], $rest_prefix );
}