WordPress函数the_tags获取文章标签使用方法解析

来自:互联网
时间:2020-03-03
阅读:

我们知道wordpress有一个the_tags函数可以获取到文章设置的所有标签,并按照你想要的形式输出。在文章页面输出标签有助于内链布局,提升SEO效果。在模板中显示标签名并链接到该标签中,如果当前页中无标签就不显示,这个函数必须使用在WordPress主循环中。就是能获取到全局变量post的地方,一般用于文章页与文章列表页。

the_tags函数位于wp-includes/category-template.php文件中:

/**
 * Retrieve the tags for a post.
 *
 * @since 2.3.0
 *
 * @param string $before Optional. Before list.
 * @param string $sep Optional. Separate items using this.
 * @param string $after Optional. After list.
 */
function the_tags( $before = null, $sep = ', ', $after = '' ) {
	if ( null === $before )
		$before = __('Tags: ');

	$the_tags = get_the_tag_list( $before, $sep, $after );

	if ( ! is_wp_error( $the_tags ) ) {
		echo $the_tags;
	}
}

可以看到the_tags函数是通过调用get_the_tag_list取得数据。

函数使用方法

<?php the_tags( $before, $sep, $after ); ?>
//$before
//在显示之前输出的内容,一般是标签链接所处容器HTML标签。
//$sep
//用来分隔的内容,你可以为空,具体效果看下面的图。
//$after
//显示在标签之后的内容,一般是标签链接所处容器HTML标签。

使用示例

默认方法

<?php the_tags(); ?>
等同于:<?php the_tags( 'Tags: ', ', ', '' ); ?>

得到:Tags:XXX, XXXX

再来一个

<?php the_tags( '<ul><li>', '</li><li>', '</li></ul>' ); ?>
返回顶部
顶部