*/ protected array $cache; public function __construct() { $this->cache = []; } protected function isRestCptRelated(string $cptName): bool { $requestUrl = $_SERVER['REQUEST_URI'] ?? ''; return false !== strpos($requestUrl, '/wp-json/') && false !== strpos($requestUrl, '/' . $cptName . '/'); } // includes any rest requests public function isAdmin(): bool { if (false === key_exists('isAdmin', $this->cache)) { $requestUri = $_SERVER['REQUEST_URI'] ?? ''; $this->cache['isAdmin'] = true === is_admin() || false !== strpos($requestUri, '/wp-json/'); } return $this->cache['isAdmin']; } // no arguments, as during ajax it's impossible to detect the specific plugin public function isAjax(): bool { if (false === key_exists('isAjax', $this->cache)) { // do not use 'is_ajax()' function, it may be not available yet $this->cache['isAjax'] = true === defined('DOING_AJAX') && true === DOING_AJAX; } return $this->cache['isAjax']; } // includes cptRelated rest requests public function isAdminCptRelated( string $cptName, string $screen = self::CPT_ANY ): bool { if (false === $this->isAdmin()) { return false; } $cacheKey = $cptName . '-' . $screen; if (true === key_exists($cacheKey, $this->cache)) { return $this->cache[$cacheKey]; } // manual detection for early calls $requestUrl = $_SERVER['REQUEST_URI'] ?? ''; $postType = sanitize_text_field($_GET['post_type'] ?? ''); $action = sanitize_text_field($_GET['action'] ?? ''); $isAdminCptRelated = false; switch ($screen) { case self::CPT_LIST: $isAdminCptRelated = false !== strpos($requestUrl, '/edit.php') && $cptName === $postType && false === strpos($requestUrl, 'page='); break; case self::CPT_ANY: case self::CPT_EDIT: // CPT_ANY requires the simple check for most of the pages // (but if we're on the edit page, CPT_ANY requires the tricky check) if (self::CPT_ANY === $screen && $cptName === $postType) { $isAdminCptRelated = true; break; } $isMyPostPage = false !== strpos($requestUrl, '/post-new.php') && $cptName === $postType; $isEditPage = false !== strpos($requestUrl, '/post.php') && 'edit' == $action; $isMyEditPage = false; if (true === $isEditPage) { $postId = (int)($_GET['post'] ?? 0); $isMyEditPage = $cptName === (string)get_post_type($postId); } $isAdminCptRelated = true === $isMyEditPage || true === $isMyPostPage; break; } $this->cache[$cacheKey] = true === $isAdminCptRelated || true === $this->isRestCptRelated($cptName); return $this->cache[$cacheKey]; } }