Search code examples
wordpressnext.jsheadless-cms

Headless Next.js Wordpress `Site Address` change breaks saving a draft


I am currently building a headless Next.js wordpress application using Vercel's example.

Currently testing in a local environment at http://localhost:3000 for Next.js and http://wordpress.test for Wordpress. So far it's working relatively well. I updated the preview link (preview_post_link) for wordpress to match the preview API endpoint in the Next.js application and updated Wordpress's site url to be point to my local Next.js environment.

Once the site url was updated the visit site,view post/page buttons now go to my Next.js app.

However, the problem I am having is that it also seems to have updated the save draft button. So now when I try to save the draft it tries to go to http://localhost:3000/wp-json/wp/v2/posts/38?_locale=user, my Next.js app and not Wordpress. Obviously because this link doesn't do anything in Next.js it throws an error.

Is this a bug in Wordpress? Or am I setting the headless URL incorrectly?


Setup

  • Wordpress version 6.1.1
  • Built my own theme

functions.php

<?php

add_filter( 'preview_post_link', 'the_preview_fix' );

function the_preview_fix($post) {
    $post = get_post();

    return home_url() . "/api/preview?secret=secret&id={$post->ID}";
}

Plugins

  • WPgraphQl version 1.14.0
  • WPGraphQL JWT Authentication version 0.4.0

Wordpress settings (No other settings have changed)


Solution

  • I figured it out! After some digging, with some guidence from ChatGPT I found this post which fixes exactly what I needed. Below is the code for anyone incase of broken link.

    I am not aware though how this will affect anything else as there must be a reason why the Wordpress developers chose the REST API route to point to the frontend and not the backend system. For my purposes however this suits me well for now.

    // change WordPress API URL to HOME URL
    add_filter('rest_url', 'wptips_home_url_as_api_url');
    function wptips_home_url_as_api_url($url) {
        $url = str_replace(home_url(),site_url() , $url);
        return $url;
    }