Skip to content

Instantly share code, notes, and snippets.

@EvanHerman
Last active May 3, 2017 12:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EvanHerman/22ce39f2ec792ab484341b36080c5ab7 to your computer and use it in GitHub Desktop.
Save EvanHerman/22ce39f2ec792ab484341b36080c5ab7 to your computer and use it in GitHub Desktop.
Populate the WordPress post tags with the values from the WordPress post categories on the save_post action hook.
<?php
/**
* Dynamically set the post tags to mirror the post categories.
*
* @action save_post
*
* @param integer $post_id The post ID.
*/
function dynamic_post_tags( $post_id ) {
// Return if this is not a 'post' or it is a revision
if ( 'post' !== get_post_type( $post_id ) || wp_is_post_revision( $post_id ) ) {
return;
}
// Retrieve the categories for this post
$categories = wp_get_post_categories( $post_id );
// Return if no categories are assigned
if ( empty( $categories ) ) {
return;
}
// Replace category IDs with the proper category names
$categories = array_map( function( $category ) {
$tax_object = get_term( $category, 'category' );
return $tax_object->name;
}, $categories );
/**
* Assign the categories to the post tags.
*
* Note: Argument 4 dictates if tags will be appended, or replace existing tags
*/
wp_set_post_terms( $post_id, $categories, 'post_tag', false );
}
add_action( 'save_post', 'dynamic_post_tags', 20 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment