Automatically tag and categorize WordPress posts on save

The function should probably check if the post already has the tag/category before adding it a second time. I should probably look into the wpispost_revision() part again as well.

Raw
<?php

add_action( 'wp_insert_post', 'update_post_terms' );

function update_post_terms( $post_id ) {
    if ( $parent = wp_is_post_revision( $post_id ) )
        $post_id = $parent;
    $post = get_post( $post_id );
    if ( $post->post_type != 'post' )
        return;

    // add a tag
    wp_set_post_terms( $post_id, 'new tag', 'post_tag', true );

    // add a category
    $categories = wp_get_post_categories( $post_id );
    $newcat    = get_term_by( 'name', 'Some Category', 'category' );
    array_push( $categories, $newcat->term_id );
    wp_set_post_categories( $post_id, $categories );
}
?>

0 comments

Reply

Cancel reply
Markdown. Syntax highlighting with <code lang="php"><?php echo "Hello, world!"; ?></code> etc.
DjangoPythonBitcoinTuxDebianHTML5 badgeSaltStackUpset confused bugMoneyHackerUpset confused bugX.OrggitFirefoxWindowMakerBashIs it worth the time?i3 window managerWagtailContainerIrssiNginxSilenceUse a maskWorldInternet securityPianoFontGnuPGThunderbirdJenkinshome-assistant-logo