routes() as $route => $args ) { register_rest_route( Config::REST_NAMESPACE, $route, $args ); } } /** * Listing the route. */ protected function routes(): array { return array( self::ROUTE . '/(?P[a-z0-9-]+)' => array( // POST rather than GET: answering stores the fetched list. 'methods' => 'POST', 'callback' => array( $this, 'render' ), 'permission_callback' => array( $this, 'require_settings_access' ), ), ); } /** * Allowing only someone who may change the plugin's settings. * * @return bool|WP_Error True, or the reason for refusing. */ public function require_settings_access() { if ( current_user_can( 'manage_options' ) ) { return true; } return new WP_Error( 'rest_forbidden', __( 'You do not have permission to change these settings.', 'kordiam' ), array( 'status' => rest_authorization_required_code() ) ); } /** * Fetching a screen's list and rendering its tables. * * @param WP_REST_Request>|WP_REST_Request $request Incoming request. * * @return WP_REST_Response The markup, or 404 for a screen that does not exist. */ public function render( $request ): WP_REST_Response { $screen = $request->get_param( 'screen' ); $page = is_string( $screen ) ? self::page( $screen ) : null; if ( null === $page ) { return Response::message( 'Unknown screen', 404 ); } // The form calls submit_button(), which REST requests do not load. if ( ! function_exists( 'submit_button' ) ) { require_once ABSPATH . 'wp-admin/includes/template.php'; } return Response::ok( array( 'html' => $page->render_live() ) ); } /** * Finding a matching screen by its slug. * * @param string $slug Screen slug, as in the admin URL. * * @return AbstractMatchingPage|null The screen, or null when there is none by that slug. */ private static function page( string $slug ): ?AbstractMatchingPage { $pages = array( new StatusMatchingPage(), new CategoryMatchingPage(), new TaskMatchingPage(), new CustomFieldsMatchingPage(), new PublicationCustomFieldsPage(), ); foreach ( $pages as $page ) { if ( $page->slug() === $slug ) { return $page; } } return null; } }