404 Error when I use the Api v4 with Wordpress Multisite -> because no "do not delete" post was generated for the subsite
I am encountering a 404 Error when I use the Api v4 with Wordpress Multisite.
My sites have urls like: mainsite.com
and subsite.com
.
I only get the 404 error on the subsite, not the main site. The data is retrieved, but there is a 404 error at the same time. This breaks the promises and makes it super awkward to use the API.
var this_works_v3 = await CRM.api3('Event', 'get');
var this_gets_a_404_result_but_the_promise_holds_the_data = await CRM.api4('Event', 'get');
var this_works_v4 = await CRM.api4('Event', 'get', {where: [["title", "LIKE", "%"]]});
I tracked it through the code and the problem occurs in the jQuery file.
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( options.hasContent && options.data ) || null );
The options.data is empty in the 404 result version because there are no parameters in the API call.
I was stumped as to what else I could do to understand this problem. Until I checked the PHP-FPM log. It turned out, there was an error being thrown in wp-content\plugins\civicrm\civicrm\CRM\Utils\System\WordPress.php:224 because post did not have ID (
post was undefined on the subsite).
/**
* @inheritDoc
*/
197 public function url(
Line 222 should be loading the post that indicates the url
222 global $post;
223 if (get_option('permalink_structure') != '') {
$script = get_permalink($post->ID);
}
if ($config->wpBasePage == $post->post_name) {
$basepage = TRUE;
}
I put the check for $post and found that on the subsite, it was not being populated. But in the main site, it was a post with the post content: 'post_content' => 'Do not delete this page. Page content is generated by CiviCRM.',
Well that's weird, the subsite doesn't have that post, but the main site says it should not be deleted. I copied the post to the subsite database table wp_3_posts
changing the ID and the guid to match the subsite. And it works!
In summary, there is a flaw in the CiviCRM setup for multisite Wordpress, because the file Wordpress.php expects there to be a post in the database so it can grab its data. The workaround was to duplicate the autogenerated "Do not delete this post" post in the subsite. No more 404 error!