wp_set_post_categories( int $post_ID, array|int $post_categories = array(), bool $append = false )

Set categories for a post.


Description Description

If the post categories parameter is not set, then the default category is going used.


Parameters Parameters

$post_ID

(int) (Optional) The Post ID. Does not default to the ID of the global $post. Default 0.

$post_categories

(array|int) (Optional) List of category IDs, or the ID of a single category.

Default value: array()

$append

(bool) (Optional) If true, don't delete existing categories, just add on. If false, replace the categories with the new categories.

Default value: false


Top ↑

Return Return

(array|false|WP_Error) Array of term taxonomy IDs of affected categories. WP_Error or false on failure.


Top ↑

Source Source

File: wp-includes/post.php

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 ) ) {
		if ( 'post' == $post_type && '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 );
}

Top ↑

Changelog Changelog

Changelog
Version Description
2.1.0 Introduced.

Top ↑

More Information More Information

If no categories are passed with a post ID that has a post type of post, the default category will be used.

Be careful, as wp_set_post_categories will overwrite any existing categories already assigned to the post unless $append is set to true.

If an ID is passed with the categories array that is not associated with a valid category, it will be stripped before the object terms are updated and from the return array.

wp_set_object_terms() performs the same function with more granular control for built in categories and can also be used to set any custom taxonomies.



Top ↑

User Contributed Notes User Contributed Notes

You must log in before being able to contribute a note or feedback.