最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

categories - chose category in plugin

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Sep 29, 2020 at 16:56 OoxOox 535 bronze badges 1
  • 1 There's no code in your question for the form or the form handler, can you edit your question to include it? – Tom J Nowell Commented Sep 29, 2020 at 18:01
Add a comment  | 

2 Answers 2

Reset to default 0

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>

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);
发布评论

评论列表(0)

  1. 暂无评论