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, 2020 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, 2020 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, 2020 at 18:33

2 Answers 2

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!

0

It is best to use the wp_after_insert_post hook which fires once a post, its terms and meta data has been saved.

See: https://developer.wordpress.org/reference/hooks/wp_after_insert_post/

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

function test( $post_id, $post ){
  $categories = get_the_terms( $post_id, 'category' );
  error_log( print_r( $categories, true ) );
}

use the get_the_terms function to get all the categories but make sure to add the right category term name. For Posts, WordPress comes with the category as the default for all posts.

You need to error_log the values since this hook will not be seen on the front-end but rather you can use the debug.log file to see all the results.

See: https://wordpress.org/support/article/debugging-in-wordpress/

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.