1

I am trying to develop a hook when save_post to get the categories but for new posts I don't get any categories and for updated posts I get the categories "before" updating the post. This should be super simple but I can't figure it out. I have been hours trying to find a solution.

This is the minimal code that I am trying to run:

add_action('save_post', 'test' , 10, 3 );
   
   function test($post_id, $post, $update){
       $categories=get_the_category($post_id);
       var_dump($categories);
   }

I am also trying to get things from $_REQUEST but its only content is this:

Array
(
    [_locale] => user
)

What am I doing wrong here?

3
  • This looks like it should work, so perhaps something else is going wrong. Are you 100% sure you're actually saving some category information with the post? Also are you sure it's not a custom taxonomy, but regular Wordpress categories?
    – mozboz
    Jul 17 '20 at 10:37
  • Also, if you're using a standard Wordpress, where/how are you seeing the output from var_dump? On a clean Wordpress with Gutenburg, this code doesn't work as it interferes with the way the page loads.
    – mozboz
    Jul 17 '20 at 11:04
  • Yeah, I am just using categories, marking/unmarking them and updating the post, that's all I am doing. I am using the Gutenberg editor. Also, I am actually using file_put_contents("log.txt",print_r($categories,true)); to see what is in that variable. Not the most elegant way but it lets me debug easily!
    – malago
    Jul 17 '20 at 18:33
1

After doing much more search... it looks like the save_post hook does not run after the post categories are updated so it will only show the categories that the post had before the update (or no categories for new posts).

I found that I need to use this hook and then everything inside my function is updated:

add_action('rest_after_insert_post', 'test' , 10, 2 );

I had no idea that was the hook I needed to use. I hope this helps someone!

Your Answer

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

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