wp_set_post_categories()WP 2.1.0

Sets categories for a post.

If the categories parameter is not set, the post will be attached to the default category.

When using this function, all old categories of the post will be removed and the specified ones will be set.

Hooks from the function

Returns

Array|false|WP_Error. identifiers - an array of term IDs that were added/attached to the post or a WP_Error object.

Usage

<?php wp_set_post_categories( $post_ID, $post_categories, $append ) ?>
$post_ID(int)
ID of the post to be attached to the categories.
$post_categories(array)
List of category IDs to which the post should be attached.
Default: array()
$append(bool)
true - add to existing categories. false - completely update categories (remove from existing and add to specified).
Default: false

Examples

1

#1 Move the post programmatically from one category to another:

Note that if we don't set the third parameter, it defaults to false, which means the categories will be replaced rather than added.

wp_set_post_categories( $post_id, [ 123 ] );

Changelog

Since 2.1.0 Introduced.

wp_set_post_categories() code WP 6.9

function wp_set_post_categories( $post_id = 0, $post_categories = array(), $append = false ) {
	$post_id     = (int) $post_id;
	$post_type   = get_post_type( $post_id );
	$post_status = get_post_status( $post_id );

	// If $post_categories isn't already an array, make it one.
	$post_categories = (array) $post_categories;

	if ( empty( $post_categories ) ) {
		/**
		 * Filters post types (in addition to 'post') that require a default category.
		 *
		 * @since 5.5.0
		 *
		 * @param string[] $post_types An array of post type names. Default empty array.
		 */
		$default_category_post_types = apply_filters( 'default_category_post_types', array() );

		// Regular posts always require a default category.
		$default_category_post_types = array_merge( $default_category_post_types, array( 'post' ) );

		if ( in_array( $post_type, $default_category_post_types, true )
			&& is_object_in_taxonomy( $post_type, 'category' )
			&& 'auto-draft' !== $post_status
		) {
			$post_categories = array( get_option( 'default_category' ) );
			$append          = false;
		} else {
			$post_categories = array();
		}
	} elseif ( 1 === count( $post_categories ) && '' === reset( $post_categories ) ) {
		return true;
	}

	return wp_set_post_terms( $post_id, $post_categories, 'category', $append );
}