*/ private array $post_types; /** * @var array */ private array $post_statuses; /** * @since 1.18.1 * * @param TargetKeywordManager $manager Imports and stores keywords. * @param array $post_types Post types that can be link targets. * @param array $post_statuses Post statuses that can be link targets. */ public function __construct( TargetKeywordManager $manager, array $post_types, array $post_statuses ) { $this->manager = $manager; $this->post_types = array() !== $post_types ? $post_types : array( 'post' ); $this->post_statuses = array() !== $post_statuses ? $post_statuses : array( 'publish' ); } /** * @since 1.18.1 * * @return array> */ public function get_hooks(): array { return array( // Not save_post: SEO plugins store their fields during or after // save_post, and when saving from the block editor those fields // arrive in the REST request only after the post itself is // written. wp_after_insert_post fires once both are saved. array( 'wp_after_insert_post', array( $this, 'on_post_saved' ), 20, 2 ), // Permanent deletion; trashing is a status change handled above. array( 'delete_post', array( $this, 'on_post_deleted' ), 10, 1 ), ); } /** * Imports the saved post's focus keywords, or removes them if the post can * no longer be a link target. * * A draft, a trashed post, a revision, or a post type that isn't scanned is * never offered as a link target, so its keywords are removed rather than * kept around to go stale. * * @since 1.18.1 * @hook wp_after_insert_post * * @param int $post_id Post id. * @param mixed $post Post object. * * @return void */ public function on_post_saved( int $post_id, $post ): void { if ( ! $post instanceof WP_Post ) { return; } $is_link_target = in_array( $post->post_type, $this->post_types, true ) && in_array( $post->post_status, $this->post_statuses, true ); if ( $is_link_target ) { $this->manager->sync( $post_id, PostModel::TYPE_POST ); return; } $this->manager->forget( $post_id, PostModel::TYPE_POST ); } /** * Removes a permanently deleted post's keywords. * * @since 1.18.1 * @hook delete_post * * @param int $post_id Post id. * * @return void */ public function on_post_deleted( int $post_id ): void { $this->manager->forget( $post_id, PostModel::TYPE_POST ); } }