score = $score ?? new AnalysisScore(); } /** * Register the save hook. * * The wp_after_insert_post hook fires once per save for the Classic editor * and once per REST create or update, in both cases after the payload is * written, so the stored score always describes the keywords just saved. */ public function register(): void { add_action( 'wp_after_insert_post', [ $this, 'handle' ], 20, 2 ); } /** * Guard, then store the score for the saved row. * * @param int $postId Current post id. * @param mixed $post Current post object. */ public function handle( int $postId, mixed $post = null ): void { // The hook supplies the saved object, but the run re-reads the row // through the score service, so this argument is deliberately unused. unset( $post ); if ( function_exists( 'wp_is_post_autosave' ) && wp_is_post_autosave( $postId ) ) { return; } if ( function_exists( 'wp_is_post_revision' ) && wp_is_post_revision( $postId ) ) { return; } $postType = function_exists( 'get_post_type' ) ? (string) get_post_type( $postId ) : ''; if ( ! AnalysisScore::isSupportedType( $postType ) ) { return; } if ( ! current_user_can( 'edit_post', $postId ) ) { return; } $this->score->store( $postId ); } }