user1048676
user1048676

Reputation: 10066

Assign multiple category IDs to a post

All, The following code adds categories to a post within 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 );

I am trying to assign post categories when I create a new post from a PHP front end webpage. I have the following on a form:

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

Then I try and process it like this:

if($_POST['category_name'] != ''){
            $cat_ids = '';
            foreach($_POST['category_name'] as $cat_name){
                 $cat_ids .= $cat_name.',';
            }
            $cat_ids = rtrim($cat_ids, ",");
            echo 'The ids are: '.$cat_ids;
        }else{
            $cat_ids = 0;
        }

When I echo out the $cat_ids variable I have 2,3 so it should work but in this example it only adds the first category id to the post instead of doing both. How can I make this work correctly?

Upvotes: 0

Views: 354

Answers (1)

wedi
wedi

Reputation: 1422

You need to create an array instead of a string with comma separated ids:

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

Reason: Converting your string to int only returns the first value: http://codepad.org/y76D3krI

Upvotes: 1

Related Questions