WordPress:將文章的分類名稱,製作成 shortcode

要用 shortcode 顯示文章分類名稱,可以在 function.php 加入以下程式碼:

function shortcode_post_category($atts=array()) {
	// get taxonomy by post type
	$tax = get_object_taxonomies(get_post_type());

	// get the categories of the taxonomy
	$cats = get_the_terms($post->ID, $tax[0]);

	$result = '';
	foreach ($cats as $cat) {
		$result = $cat->name;
		return $result;
	}
	return $result;
}
add_shortcode('post_category', 'shortcode_post_category');


參考文章:

How To: Get Single Post Category With a WordPress Shortcode