查看相关source 在里面/wp-includes/category-template.php
, 我们可以看到,没有直接的方法来添加data
属性。
/**
* Filters the data used to generate the tag cloud.
*
* @since 4.3.0
*
* @param array $tags_data An array of term data for term used to generate the tag cloud.
*/
$tags_data = apply_filters( \'wp_generate_tag_cloud_data\', $tags_data );
$a = array();
// Generate the output links array.
foreach ( $tags_data as $key => $tag_data ) {
$class = $tag_data[\'class\'] . \' tag-link-position-\' . ( $key + 1 );
$a[] = sprintf(
\'<a href="%1$s"%2$s class="%3$s" style="font-size: %4$s;"%5$s>%6$s%7$s</a>\',
esc_url( $tag_data[\'url\'] ),
$tag_data[\'role\'],
esc_attr( $class ),
esc_attr( str_replace( \',\', \'.\', $tag_data[\'font_size\'] ) . $args[\'unit\'] ),
$tag_data[\'aria_label\'],
esc_html( $tag_data[\'name\'] ),
$tag_data[\'show_count\']
);
}
我们在这里所能做的就是劫持(或偷渡)
arial-label
属性并将数据属性附加到此处:
add_filter( \'wp_generate_tag_cloud_data\', function( $tags_data ) {
$body_class = get_body_class();
foreach( $tags_data as $key => $tag ) {
if ( in_array( \'tag-\' . $tag[\'id\'], $body_class ) ) {
$tags_data[$key][\'class\'] = $tags_data[$key][\'class\'] ." active-tag";
$tags_data[$key][\'aria_label\'] .= \' data-text="\' . esc_attr( $tag[\'name\'] ) . \'" \';
}
}
return $tags_data;
});
为了进行测试,我使用这个小片段向body类添加了一个特定的术语,这样看起来就像我在某个特定术语的术语归档页面上一样:
add_filter( \'body_class\', \'wpse_body_class\' );
function wpse_body_class( $classes ) {
$classes[] = \'tag-49\';
return $classes;
}
正在查看
/wp-includes/category-template.php
再进一步,还有
wp_generate_tag_cloud
过滤器,它允许我们解析HTML并根据自己的喜好对其进行修改,但这有点痛苦,所以我改为使用aria属性hack。
/**
* Filters the generated output of a tag cloud.
*
* The filter is only evaluated if a true value is passed
* to the $filter argument in wp_generate_tag_cloud().
*
* @since 2.3.0
*
* @see wp_generate_tag_cloud()
*
* @param array|string $return String containing the generated HTML tag cloud output
* or an array of tag links if the \'format\' argument
* equals \'array\'.
* @param WP_Term[] $tags An array of terms used in the tag cloud.
* @param array $args An array of wp_generate_tag_cloud() arguments.
*/
return apply_filters( \'wp_generate_tag_cloud\', $return, $tags, $args );