2

I have been testing out the JSON REST API the past few days with some pretty good results however I have run into a bit of a barrier when making a post.

I need to hook into the post call before the post is made, however I can't for the life of me find any way to do this. It's fairly important that this is possible, otherwise I may well have to come up with my own solution (which isn't ideal!).

The nearest I have come to being able to do this is by using the following action:

add_action('json_prepare_post', 'receive_post_data');

However this is called after the post has been made.

Does anyone have any ideas or is it simply not possible? This gitHub thread pretty much says it isn't possible.

Cheers!

2 Answers 2

2

json_prepare_post should be rest_prepare_post or rest_prepare_{post_type}

0

Today I recommend to use rest_pre_insert_{post type} (for Posts rest_pre_insert_post, for Pages rest_pre_insert_post) because it runs exactly before a post is inserted/updated by wp_insert_post() function.

For publishing new posts:

add_filter( 'rest_pre_insert_post', 'rudr_new_post', 25, 2 );

function rudr_new_post( $post, $request ) {

    if( isset( $post->ID ) ) {
       return $post;
    }

    // creating a new post

    return $post;

}

almost the same code but for post updates:

add_filter( 'rest_pre_insert_post', 'rudr_update_post', 25, 2 );

function rudr_update_post( $post, $request ) {

    if( ! isset( $post->ID ) ) {
        return $post;
    }

    // updating an existing post with ID = $post->ID

    return $post;

}

And don't forget that $post here is not a WP_Post object. More example here https://rudrastyh.com/wordpress/prevent-trashed-posts-updates-rest-api.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.