我想在wordpress中制作帖子编辑页面前端,我可以用这段代码显示所有类别
<?php
$include = array();
$categories = get_terms('category', array(
'include' => $include,
'hide_empty' => false,
));
$categories_count = count( $categories );
if ( $categories_count > 1 ) :
?>
<div class="form-categories">
<ul>
<?php
foreach ( $cats as $cat ) {
echo '<li class="form-categories-item"><input type="checkbox" id="post_cat-' . esc_attr( $cat->term_id ) . '" name="post_category[]" value="' . esc_attr( $cat->term_id ) . '" /><label for="post_cat-' . esc_attr( $cat->term_id ) . '">' . esc_attr( $cat->name ) . '</label></li>';
}
?>
</ul>
</div>
<?php endif; ?>
如何在创建帖子时将已选中标记添加到所选类别?
谢谢
答案 0 :(得分:1)
您可以尝试以下代码:
<?php
$include = array();
$categories = get_terms('category', array(
'include' => $include,
'hide_empty' => false,
));
$categories_count = count( $categories );
// get post categories
$post_cats = get_the_terms( get_the_ID(), 'category' );
$post_cats_arr = array();
foreach ( $post_cats as $post_cat )
{
$post_cats_arr[] = $post_cat->term_id;
}
if ( $categories_count > 1 ) :
?>
<div class="form-categories">
<ul>
<?php
foreach ( $categories as $cat )
{
$checked = '';
if ( in_array( $cat->term_id, $post_cats_arr ) )
{
$checked = 'checked';
}
echo '<li class="form-categories-item"><input type="checkbox" checked="' . $checked . '" id="post_cat-' . esc_attr( $cat->term_id ) . '" name="post_category[]" value="' . esc_attr( $cat->term_id ) . '" /><label for="post_cat-' . esc_attr( $cat->term_id ) . '">' . esc_attr( $cat->name ) . '</label></li>';
}
?>
</ul>
</div>
<?php endif; ?>
谢谢!