I suggest post status transitions that runs only when your set conditions are met.
Example:
add_action( 'transition_post_status', 'add_awesome_terms', 10, 3 );
function add_awesome_terms( $new_status, $old_status, $post ) {
// only run when it's a page, new status is publish and old status isn't publish
if ( $post->post_type == 'page' && $new_status == 'publish' && $old_status != 'publish' ) {
// do whatever you need here, it runs only when your set conditions are met
wp_insert_term( $post->post_title, 'mypages' );
}
}
Little bonus: you already have a $post object and you have access to all the $post variables.
You might want to add your own conditions to make it bulletproof. It’s currently ran every time new status is publish and old is not publish. It all depends how your page/post management is set up.
Possible post statuses:
new– when there’s no previous statuspublish– a published post or pagepending– a post pending reviewdraft– a post in draft statusauto-draft– a newly created post with no contentfuture– a post scheduled to publish in the futureprivate– not visible to users who are not logged ininherit– a revision or attachmenttrash– post is in the trash
Don’t forget to use $post variables to your advantage, you already have it! Variables are listed here.