我为用户-用户类别添加了一个自定义分类法。
使用下面的代码,我能够在每个编辑用户配置文件页面中输出自定义分类:
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 '<br />';
}
}
上面的代码只是显示一个复选框列表,按term_id排序。
当然,我希望以与自定义分类法术语在自定义帖子类型中显示相同的方式显示它们(复选框的可滚动列表,子术语缩进并位于其父术语下方)。上面的代码没有按父母/子女的顺序显示术语。
有没有一个WP函数我可以通过我的分类法&术语,以创建我在上面一段中描述的内容?还是我必须手动操作?
感谢
简短回答:
是的,有。它们被称为post_categories_meta_box()
和post_tags_meta_box()
,这取决于您使用的分类法的类型。
长答案:
这类问题可以通过检查WP核心代码来回答。
以下是我如何回答这个问题的演练:
在admin中编辑页面会导致url为wp-admin/post.php
。因此,检查该文件(post.php).
在该文件中快速搜索"tax"没有结果,所以我们至少可以查看case 'edit'
部分,因为我们知道我们正在进行编辑。我们可以看到它包括一个文件edit-form-advanced.php
。
因此,检查该文件(编辑表单advanced.php)
快速搜索"税收"进入了一个看起来很有前景的领域。
在这里,我们看到他们调用get_taxonomy
,然后返回的get_taxonomy
对象有一个名为meta_box_cb
的回调,所以要进行跨文件搜索。我们找到了几个实例,但taxonomy.php
中的实例是最有前途的(因为文件名),所以让我们看看那里。
似乎(在taxonom.php的第430行附近)有一对回调函数—post_categories_meta_box
和post_tags_meta_box
,WP核心正在使用。让我们检查一下——对function post_categories_meta_box
进行跨文件搜索,我们发现这两个函数都存在于文件meta-boxes.php
中。对这些功能的评论非常好,并告诉我们您的要求:"显示帖子类别表单字段"。
有了这些信息,我们可以询问谷歌,我们可以找到功能的WP文档:
post_categories_meta_box
和
post_tags_meta_box