在WordPress中,想要获取指定分类ID的URL需要使用WordPress的内置函数get_category_link()。当然还有其他方法也可以,下面给大家列出几种获取分类的URL方法:
1. 使用 get_category_link() 函数
get_category_link() 函数可以直接获取到指定分类的链接。你需要提供分类的ID作为参数。
$category_id = 1; // 替换为你的分类ID
$category_link = get_category_link($category_id);
echo $category_link;
2. 使用 get_term_link() 函数
get_term_link() 函数是更通用的一种方式,它可以用来获取任何类型的术语(term)的链接,包括分类。你需要提供术语的对象或者其ID和taxonomy(分类的taxonomy是category)。
$category = get_category($category_id); // 获取分类对象
$category_link = get_term_link($category->term_id, 'category');
echo $category_link;
3.实用方法:
在循环中使用 get_category_link() 或 get_term_link()
<?php if ( 'category' == get_post_type() ) { ?>
<h2><?php _e( 'Category:', 'textdomain' ); ?></h2>
<ul>
<?php foreach((get_the_category($post->ID)) as $category) { ?>
<li><a href="<?php echo esc_url( get_category_link( $category->term_id ) ); ?>"><?php echo esc_html($category->name); ?></a></li>
<?php } ?>
</ul>
<?php } ?>