1

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!

  • You could also use post status transitions to add new term only when post is published. – N00b May 13 '16 at 11:25
  • Can you give an example? I never worked with post status transitions before and I was not able to implement the hook. Also I can not update the terms when the page title changes with this method, right? – Jekyll May 13 '16 at 11:50
1

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.

  • It depends.. Do you have only one term per page? – N00b May 13 '16 at 12:17
  • Does these terms have any front-end value for users or it's used for something else (admin or developer stuff)? Using ID would be much better, it would never need to change. – N00b May 13 '16 at 12:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.