Insert term when page is published – avoid duplicates after edits

So i want to dynamically add terms to a custom taxonomy named after new pages when these are published. Problem I have is that when you edit the page titles, another term will be added to the taxonomy.

This snippet is from this answer, it works for inserting terms.

function add_page_term( $post_ID ) {
$post = get_post( $post_ID );
wp_insert_term( $post->post_title, 'mypages' );
add_action( 'publish_page', 'add_page_term' );

So far I tried to first get the post_ID and then replace it with the post_title using the pre_insert_term hook or to override the value with str_replace but had no success. Any ideas on this? Help is highly appreciated. Thanks in advance!

Solutions Collecting From Web of "Insert term when page is published – avoid duplicates after edits"

I suggest post status transitions that runs only when your set conditions are met.


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.