Php 添加包含可供选择的类别的列表,并将其另存为帖子的类别

Php 添加包含可供选择的类别的列表,并将其另存为帖子的类别,php,wordpress,widget,Php,Wordpress,Widget,我有一个解决方案,用户现在可以将类别添加到他们的帖子中。问题:他们不知道哪些已经存在,哪些已经存在。因此,我想选择一条用户可以选择(复选框?)现有类别的路线 我的问题是:如何正确地做到这一点 我的代码如下: if(isset($_POST['entry']) AND !$_POST['entry'] == ""): $my_post = array(); $my_post['post_title'] = $_POST['title'];

我有一个解决方案,用户现在可以将类别添加到他们的帖子中。问题:他们不知道哪些已经存在,哪些已经存在。因此,我想选择一条用户可以选择(复选框?)现有类别的路线

我的问题是:如何正确地做到这一点

我的代码如下:

                           if(isset($_POST['entry']) AND !$_POST['entry'] == ""):
$my_post = array();

$my_post['post_title']   = $_POST['title'];
$my_post['post_content'] = $_POST['entry'];
$my_post['post_status']  = 'publish';

$cat_name             = sanitize_text_field( $_POST['newcat'] );
$my_post ['cat_name'] = $cat_name;

$category_id = get_cat_ID( $_POST['newcat'] );

if ( ! $category_id ) {
    if ( ! is_admin() ) {
        die();
    }
$args = array(
    'description' => "Category description",
    'parent' => 0);
    $category_id = wp_insert_term( $_POST['newcat'], "category", $args );
}

$my_post['post_author'] = get_current_user_id();

$my_post['tax_input'] = array('category' => $category_id);


wp_insert_post( $my_post );
然后我显示了下拉式类别,但在添加类别复选框时,我无法保存我的选择

$categories=get_categories();   foreach($categories as $category) {     echo "<input type='checkbox' name='mychecky' value='$category->term_id' />";    echo $category->cat_name;
    echo '<br>';    }
$categories=get_categories();foreach($categories as$category){echo”“;echo$category->cat_name;
回音“
”;}

如何根据我的帖子的清单保存所选类别?

在您的表单中,清单应接受多个值,因此它必须是一个数组。HTML表单中的数组具有方括号
[]
,因此您的复选框名称应类似于
mychecky[]
。复选框输入的完整代码:

$categories = get_categories();
foreach($categories as $category) {
   echo "<label><input type='checkbox' name='mychecky[]' value='$category->term_id' />$category->cat_name</label><br>";
}

您可以将方法与分类法结合使用,也可以使用内置的
post\u类别
,检查文档的功能。

表单中的检查表应接受多个值,因此它必须是一个数组。HTML表单中的数组具有方括号
[]
,因此您的复选框名称应类似于
mychecky[]
。复选框输入的完整代码:

$categories = get_categories();
foreach($categories as $category) {
   echo "<label><input type='checkbox' name='mychecky[]' value='$category->term_id' />$category->cat_name</label><br>";
}
您可以将您的方法与分类法结合使用,也可以使用内置的
post\u category
,检查文档的功能