Reputation: 193
I am trying to make post edit page front-end in wordpress , I can show all the categories with this code
<?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; ?>
how can I add checked tag to selected categories when creating post?
thanks
Upvotes: 1
Views: 706
Reputation: 349
You can try this code below :
<?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; ?>
Thanks!
Upvotes: 1