当更改 WordPress 后台管理面板域名后,站点健康工具提示我 REST API 无法正常工作。因为我用的是经典编辑器和经典小工具,所以这个问题没有给我带来太大影响。不过既然已经知道有问题,我决定还是找一找解决这一问题的办法。幸好,这个问题并不复杂。
站点健康工具显示了如下信息:
The REST API encountered an unexpected result The REST API is one way that WordPress and other applications communicate with the server. For example, the block editor screen relies on the REST API to display and save your posts and pages. When testing the REST API, an unexpected result was returned: REST API Endpoint: https://www.draftposts.com/wp-json/wp/v2/types/post?context=edit REST API Response: (403) Forbidden
我们打开的是 “admin.draftposts.com” 管理网站,但 REST API Endpoint 仍然在使用 “www.draftposts.com” 域名。问题就出在这里。我们需要更改 REST API Endpoint,把 “www” 换成 “admin”。
“www” 站点的 403 Forbidden 错误实际上“符合预期”,因为我们毕竟没有在 “www” 站点登录。
根据 “rest-api.php”,REST URL 是基于 home_url(即 “WP_HOME”)而非 site_url(即我们之前设置的 “WP_SITEURL”)生成的。我们可以使用 “rest_url” filter 来把 home_url 替换成 site_url。
给 WordPress 网站添加如下代码:
// Fix WordPress REST API - Replace home_url with site_url // https://developer.wordpress.org/reference/functions/get_rest_url/ // https://developer.wordpress.org/reference/hooks/rest_url/ // START add_filter( 'rest_url', 'draftposts_resturl_replace_homeurl_with_siteurl' ); function draftposts_resturl_replace_homeurl_with_siteurl( $url ) { return str_replace( home_url(), site_url(), $url); } // END
现在再次测试,发现问题已经得到解决。