is_admin() returns false in save_post hook with Gutenberg editor

I have a plugin that implements a REST API that needs to be notified when an admin adds one of my supported shortcodes to a page or post. I hook save_post with my function like this.

        add_action( 'save_post', 'detect_shortcodes');

However, when I update from the editor, it does an ajax call that instantiates my plugin. The first thing it does is determine whether to load public or admin hooks like this.

    if(is_admin())
    {
        $this-define_admin_hooks();
    }
    else
    {
        $this-define_public_hooks();
    }

Of course, my detect_shortcodes function is on the admin side. With the TinyMCE editor, this worked correctly, and instantiated my admin hooks. With the Gutenberg editor, is_admin() returns false.

Is there a replacement for is_admin() that will work with Gutenberg ajax calls?

Topic block-editor wp-remote-request shortcode Wordpress

Category Web


You could try with the following instead to detect if rest

if ( is_admin() || defined( 'REST_REQUEST' ) && REST_REQUEST ) {

}

I have landed on this embarrassing hack. I hope someone can improve this answer and make it less brittle. Perhaps read taxonomy to find current pages and posts endpoints?

    $pagesajax = 'wp-json/wp/v2/pages';
    $postsajax = 'wp-json/wp/v2/posts';

    if(is_admin() || !empty($_SERVER['REQUEST_URI']) &&
        strpos($_SERVER['REQUEST_URI'], $pagesajax) !== false ||
        strpos($_SERVER['REQUEST_URI'], $postsajax) !== false)
    {
        ... load admin side ...
    }

I think this hook should work:

function run_hooks( $post, $request ) {
    // Here you can run your hooks
}
add_action('rest_after_insert_post', 'run_hooks', 10, 2);

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.