BarahaSoft

How to fetch post tags in wordpress api?

BarahaSoft
Share It

we know WordPress provides rest API in default.Sometime we need to customize (add/remove ) fields in response. In this blog we see how post tags can be added in our response without any plugin. An application programming interface(API) is a computing interface which defines interactions between multiple software intermediaries. It defines the kinds of calls or requests that can be made, how to make them, the data formats that should be used, the conventions to follow, etc. Here we add following few lines of codes in functions.php inside theme.

// add post tags in response
add_action('rest_api_init', 'bs_rest_api_hooks');

function bs_rest_api_hooks() {

	register_rest_field(
		'post',
		'tags',
		array(
			'get_callback' => 'bs_get_tags',
		)
	);

}

function bs_get_tags($object, $field_name, $request) {

	$strTags = "";

	$tags = get_the_tags($object["id"]);
	if (!empty($tags)) {
		foreach ($tags as $key => $value) {
			if (!empty($strTags)) {
				$strTags .= ",";
			}

			$strTags .= getObjectValue($value, "name","");
		}
	}
	return $strTags;
}


Share It