I am building an application using WP REST API. Ideally, users are able to post only if they have a subscription. Here is how I plan to make things work:

  1. Set expire_by user meta when they sign up. This key is set to a timestamp 30 days from now. (i.e. users are given a 30 day free trial). I am using strtotime('+30 days') to set expire_by at the time of sign up.
  2. Users can post if current time is less than expire_by timestamp. So, I am doing similar to this:
if(strtomtime('now')>get_the_author_meta('expire_by', $user_id)){
// let the user post
} else {
// prevent from posting
// show an error 
  1. Inside subscriptions page, users are redirected to payment gateway. Once the payment is complete, users' expire_by meta key is set to strtotime('+30 days')

The problem is step 2. I can't seem to make it work with transition_post_status hook. So far, I have tried this:

add_action( 'transition_post_status', 'check_plan_validity', 11, 3 );
 function check_plan_validity( $new_status, $old_status, $post ) {
     $expire_by = (int) get_the_author_meta('expire_by', $post->post_author);
     $now = strtotime("now");
         $error['error'] = 'Plan expired';
         echo json_encode($error);

Using the above code gives out a 500 server error on wp/v2/posts/ routes. My question is how can I prevent the post update and show an error on REST routes. I have tried pre_post_update hook as well. But no dice. I have also tried this but the method described there only shows error on admin dashboard. But I want a solution for REST routes.

My logic can be wrong. But I am open to suggestions. Is there any better way I can use to prevent post update/create? I don't want to use any subscription plugin because most of them do not have any support for REST routes.

Any help is much appreciated.

  • You might want to use rest_pre_insert_{$post_type} instead of the transition_post_status hook. But you should check my answer here. – Sally CJ Apr 22 at 13:24
  • The filter you mentioned do not have any access to user's data. – abhisek Apr 23 at 10:12
  • Well, the callback receives a post data as the first argument, so if the post type supports author, then you can use $post->post_author to retrieve the user ID, similar to what you've done with the transition_post_status filter. – Sally CJ Apr 24 at 1:25
  • Nope. That is incorrect. I did a var_dump($post) inside rest_pre_insert_post and it just contains title and post_content – abhisek Apr 29 at 14:14
  • Not 100% "incorrect"... but anyway, the REST API also uses the wp_insert_post function which sets the post author to the current user if the post_author parameter is not explicitly specified. Therefore you could use wp_get_current_user() to access the user data. – Sally CJ Apr 29 at 15:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.