wp_link_category_checklist()
云策文档标注
概述
wp_link_category_checklist() 函数用于输出链接分类的复选框列表元素,适用于WordPress后台管理界面。它根据链接ID获取已选分类,并生成HTML复选框供用户选择。
关键要点
- 函数接受可选参数 $link_id(默认0),用于指定链接ID以获取已选分类。
- 使用 get_terms() 检索 'link_category' 分类法中的所有分类,按名称排序。
- 通过 wp_get_link_cats() 获取指定链接的分类ID,若无则默认选中ID为1的分类。
- 输出每个分类的复选框,使用 esc_html() 和 apply_filters('the_category') 处理分类名称。
- 函数在WordPress 2.5.1版本引入,主要用于后台的链接管理界面。
代码示例
function wp_link_category_checklist( $link_id = 0 ) {
$default = 1;
$checked_categories = array();
if ( $link_id ) {
$checked_categories = wp_get_link_cats( $link_id );
if ( ! count( $checked_categories ) ) {
$checked_categories[] = $default;
}
} else {
$checked_categories[] = $default;
}
$categories = get_terms(
array(
'taxonomy' => 'link_category',
'orderby' => 'name',
'hide_empty' => 0,
)
);
if ( empty( $categories ) ) {
return;
}
foreach ( $categories as $category ) {
$cat_id = $category->term_id;
$name = esc_html( apply_filters( 'the_category', $category->name, '', '' ) );
$checked = in_array( $cat_id, $checked_categories, true ) ? ' checked="checked"' : '';
echo '<input type="checkbox" name="link_category[]" value="' . $cat_id . '"' . $checked . '> ' . $name . '<br>';
}
}注意事项
- 函数依赖于 'link_category' 分类法,确保该分类法已正确注册。
- 使用 apply_filters('the_category') 允许开发者过滤分类名称输出。
- 函数主要用于后台,如 link_categories_meta_box() 和 dropdown_link_categories() 中调用。
原文内容
Outputs a link category checklist element.
Parameters
$link_idintoptional-
The link ID. Default 0.
Source
function wp_link_category_checklist( $link_id = 0 ) {
$default = 1;
$checked_categories = array();
if ( $link_id ) {
$checked_categories = wp_get_link_cats( $link_id );
// No selected categories, strange.
if ( ! count( $checked_categories ) ) {
$checked_categories[] = $default;
}
} else {
$checked_categories[] = $default;
}
$categories = get_terms(
array(
'taxonomy' => 'link_category',
'orderby' => 'name',
'hide_empty' => 0,
)
);
if ( empty( $categories ) ) {
return;
}
foreach ( $categories as $category ) {
$cat_id = $category->term_id;
/** This filter is documented in wp-includes/category-template.php */
$name = esc_html( apply_filters( 'the_category', $category->name, '', '' ) );
$checked = in_array( $cat_id, $checked_categories, true ) ? ' checked="checked"' : '';
echo '<li id="link-category-', $cat_id, '"><label for="in-link-category-', $cat_id, '" class="selectit"><input value="', $cat_id, '" type="checkbox" name="link_category[]" id="in-link-category-', $cat_id, '"', $checked, '/> ', $name, '</label></li>';
}
}
Hooks
- apply_filters( ‘the_category’, string $thelist, string $separator, string $parents )
-
Filters the category or list of categories.
Changelog
| Version | Description |
|---|---|
| 2.5.1 | Introduced. |