wp_ajax_get_tagcloud()
云策文档标注
概述
wp_ajax_get_tagcloud() 是一个 WordPress AJAX 处理函数,用于通过 AJAX 请求获取标签云数据。它验证用户权限和输入,检索指定分类法的术语,并生成标签云输出。
关键要点
- 函数通过 AJAX 处理标签云请求,确保数据安全性和用户权限检查。
- 使用 sanitize_key() 清理输入,防止安全漏洞。
- 验证当前用户是否具有 assign_terms 权限,确保操作授权。
- 通过 get_terms() 检索最多 45 个术语,按计数降序排列。
- 使用 wp_generate_tag_cloud() 生成标签云,设置 filter 为 0 以输出原始数据。
- 错误处理包括检查术语是否存在、是否为 WP_Error,并相应调用 wp_die()。
代码示例
if ( ! isset( $_POST['tax'] ) ) {
wp_die( 0 );
}
$taxonomy = sanitize_key( $_POST['tax'] );
$taxonomy_object = get_taxonomy( $taxonomy );
if ( ! $taxonomy_object ) {
wp_die( 0 );
}
if ( ! current_user_can( $taxonomy_object->cap->assign_terms ) ) {
wp_die( -1 );
}
$tags = get_terms(
array(
'taxonomy' => $taxonomy,
'number' => 45,
'orderby' => 'count',
'order' => 'DESC',
)
);注意事项
- 函数依赖于 POST 参数 'tax',必须确保 AJAX 请求正确传递此参数。
- 权限检查基于 taxonomy_object->cap->assign_terms,需确保用户角色配置正确。
- 输出为原始标签云 HTML,不应用过滤器,适合直接嵌入前端。
- 错误时使用 wp_die() 终止执行,需在前端处理相应响应。
原文内容
Handles getting a tagcloud via AJAX.
Source
function wp_ajax_get_tagcloud() {
if ( ! isset( $_POST['tax'] ) ) {
wp_die( 0 );
}
$taxonomy = sanitize_key( $_POST['tax'] );
$taxonomy_object = get_taxonomy( $taxonomy );
if ( ! $taxonomy_object ) {
wp_die( 0 );
}
if ( ! current_user_can( $taxonomy_object->cap->assign_terms ) ) {
wp_die( -1 );
}
$tags = get_terms(
array(
'taxonomy' => $taxonomy,
'number' => 45,
'orderby' => 'count',
'order' => 'DESC',
)
);
if ( empty( $tags ) ) {
wp_die( $taxonomy_object->labels->not_found );
}
if ( is_wp_error( $tags ) ) {
wp_die( $tags->get_error_message() );
}
foreach ( $tags as $key => $tag ) {
$tags[ $key ]->link = '#';
$tags[ $key ]->id = $tag->term_id;
}
// We need raw tag names here, so don't filter the output.
$return = wp_generate_tag_cloud(
$tags,
array(
'filter' => 0,
'format' => 'list',
)
);
if ( empty( $return ) ) {
wp_die( 0 );
}
echo $return;
wp_die();
}
Changelog
| Version | Description |
|---|---|
| 3.1.0 | Introduced. |