chose category in plugin

I am making a plugin to upload records and I want to put the option to choose category, also I would like those categories to be the ones that are normally created with wordpress, but I don’t know if can

How do I put the option to choose category in the form?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

IDs are your friends. Get the category list using get_category (i’m assuming we are talking about the in-built WordPress “category” taxonomy, which slug is category).

$categories = get_categories( array(
    'hide_empty' => false // This is optional
) );

Use the obtained category list in the output of your <select> field:

 <?php // get $selected_term_id from somewhere ?> 
 <select name="category_id">
       <?php foreach( $categories as $category ) : ?>
           <?php $is_selected = $category->term_id == $selected_term_id ? 'selected' : ''; ?> 
           <option value="<?php esc_attr_e( $category->term_id ); ?>" <?php echo $is_selected; ?>><?php esc_html_e( $category->cat_name ); ?></option>
       <?php endforeach; ?>
 </select>

Method 2

you can try this code:

$parent_cat = get_query_var('cat');
wp_list_categories("child_of=$parent_cat&show_count=1");

you will get a list of top-level categories at the output

if you need an example of selecting a category, you can do this:

$args = array(
    'taxonomy'      => 'tags',
    'parent'        => 0, // get top level categories
    'orderby'       => 'name',
    'order'         => 'ASC',
    'hierarchical'  => 1,
    'pad_counts'    => 0
);

$categories = get_categories( $args );

echo '<select name="category_id">';

foreach ( $categories as $category ){
    echo '<option value="'.$category->ID.'">'.$category->name.'</option>';               
}

echo '</select>';

after submitting the form, you need to process the POST request:

wp_set_post_categories( $your_record_id,  array( $_POST['category_id'] ), true);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x