My website allows uses to post posts of a custom post type (“place”).

I would like to display the same “Categories” meta box seen in WordPress dashboard when you add or edit a post on frontend:
backend categories meta box

This is because the “Categories” meta box or hierarichical checkboxes is simply the best way to view and edit the categories a post belongs to.

How do I the “Categories” meta box on frontend?

I do know JQuery so feel free to throw in JQuery stuffs if any.
I would strongly prefer an approach to replicate what WordPress does for adding/ editing a post in backend, instead of a hack from scratch.

1 Answer
1

Try wp_terms_checklist() / wp_category_checklist. It will output a list of checkboxes named post_category.

You might need to include the source file too, because it’s defined within administration files.

Or use a custom walker:

class MyCategoryWalker extends Walker_Category{

  public function start_el(&$output, $term, $depth, $args){

    $args = wp_parse_args(array(
      'name'    => 'my_category_input',
      'checked' => array(),

    ), $args);

    extract($args);

    $checked = checked(in_array($term->term_id, $checked));

    ob_start(); ?>   

    <li>
      <input type="checkbox" <?php $checked; ?> id="category-<?php print $term->term_id; ?>" name="<?php print $name; ?>[]" value="<?php print $term->term_id; ?>" />
      <label for="category-<?php print $term->term_id; ?>">
        <?php print esc_attr($term->name); ?>
      </label>       

    <?php // closing LI is added inside end_el

    $output .= ob_get_clean();
  }
}

Use it like:

wp_list_categories(array(
  'walker'   => new MyCategoryWalker(),
  'name'     => 'my_category_input',       // name of the input
  'selected' => array(2, 5, 10),           // checked items (category IDs)
));

Leave a Reply

Your email address will not be published. Required fields are marked *