我已经为用户添加了自定义分类 - 用户类别 .
使用下面的代码,我可以在每个编辑用户配置文件页面中输出自定义分类:
function show_user_category( $user ) {
//get the terms that the user is assigned to
$assigned_terms = wp_get_object_terms( $user->ID, 'user_category' );
$assigned_term_ids = array();
foreach( $assigned_terms as $term ) {
$assigned_term_ids[] = $term->term_id;
}
//get all the terms we have
$user_cats = get_terms( 'user_category', array('hide_empty'=>false) );
echo "<h3>User Category</h3>";
//list the terms as checkbox, make sure the assigned terms are checked
foreach( $user_cats as $cat ) { ?>
<input type="checkbox" id="user-category-<?php echo $cat->term_id ?>" <?php if(in_array( $cat->term_id, $assigned_term_ids )) echo 'checked=checked';?> name="user_category[]" value="<?php echo $cat->term_id;?>"/>
<?php
echo '<label for="user-category-'.$cat->term_id.'">'.$cat->name.'</label>';
echo '
';
}
}
上面的代码只显示一个复选框列表,按term_id排序 .
当然,我希望以与自定义分类术语在自定义帖子类型中显示的相同方式显示它们(可滚动的复选框列表,其中子项缩进并在其父术语下面) . 上面的代码不会按照父母/子女的顺序显示这些条款 .
是否有WP功能我可以通过我的分类和术语,以创建我在上面段落中描述的内容?或者我必须手动完成吗?
谢谢
1 回答
Short answer:
是的,有 . 它们被称为
post_categories_meta_box()
和post_tags_meta_box()
,具体取决于您使用的分类法类型 .Long answer:
这是可以通过检查WP核心代码来回答的问题 .
以下是我如何回答这个问题的演练:
在admin中编辑页面会导致
wp-admin/post.php
的网址 . 因此,检查该文件(post.php) .在该文件中快速搜索"tax"没有任何结果,所以我们至少可以查看
case 'edit'
部分,因为我们知道我们正在进行编辑 . 我们可以看到它包含一个文件edit-form-advanced.php
.所以,检查一下这个文件(edit-form-advanced.php)
快速搜索“税”进入一个看起来很有希望的领域 .
在这里我们看到他们调用
get_taxonomy
,然后返回的get_taxonomy
对象有一个名为meta_box_cb
的回调 - 所以对它进行跨文件搜索 . 我们找到了几个实例,但taxonomy.php
中的实例是最有希望的(因为文件名),所以让我们看看 .看来(在taxonomy.php的第430行附近)有一对回调函数 - WP核心正在使用的
post_categories_meta_box
和post_tags_meta_box
. 让我们看看它们 - 对function post_categories_meta_box
进行跨文件搜索,我们发现meta-boxes.php
文件中存在这两个函数 . 对功能的评论很好,并告诉我们你在问什么:"Display post categories form fields" .有了这些信息,我们可以向Google询问,我们会找到有关这些功能的WP文档:
post_categories_meta_box
和
post_tags_meta_box