Php 为一篇文章分配多个类别ID

Php 为一篇文章分配多个类别ID,php,Php,全部,, 以下代码将类别添加到Wordpress中的帖子: $bmt_post = array( 'post_title' => wp_strip_all_tags( $title ), 'post_content' => wp_strip_all_tags( $information ), 'post_status' => 'publish', 'post_category' =>

全部,, 以下代码将类别添加到Wordpress中的帖子:

$bmt_post = array(
          'post_title'    => wp_strip_all_tags( $title ),
          'post_content'  => wp_strip_all_tags( $information ),
          'post_status'   => 'publish',
          'post_category' => array( 2,3 )
        );

$post_id = wp_insert_post( $bmt_post );
当我从PHP前端网页创建新帖子时,我试图分配帖子类别。我在表格上有以下内容:

echo '<input type="checkbox" name="category_name[]" value="'.$category->term_id.'"> '.$category->name.'<br>';

当我回显
$cat_id
变量时,我有2,3,所以它应该可以工作,但在本例中,它只将第一个类别id添加到帖子中,而不是同时执行这两个操作。如何使其正常工作?

您需要创建一个数组,而不是使用逗号分隔的ID创建字符串:

foreach($_POST['category_name'] as $cat_name){
    if ( is_int( $cat_name ) ) {
        $cat_ids[] = $cat_name;
    }
}
var_dump( $cat_ids );

原因:将字符串转换为int只返回第一个值:

这是答案的一部分。我还必须将这个
'post\u category'=>数组(2,3)
更新为
'post\u category'=>$cat\u id
,然后它就工作了。
foreach($_POST['category_name'] as $cat_name){
    if ( is_int( $cat_name ) ) {
        $cat_ids[] = $cat_name;
    }
}
var_dump( $cat_ids );