Insert term when page is published – avoid duplicates after edits

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 status
  • publish – a published post or page
  • pending – a post pending review
  • draft – a post in draft status
  • auto-draft – a newly created post with no content
  • future – a post scheduled to publish in the future
  • private – not visible to users who are not logged in
  • inherit – a revision or attachment
  • trash – post is in the trash

Don’t forget to use $post variables to your advantage, you already have it! Variables are listed here.