I add some custom fields to an category with select boxes with true or false. But if the term meta not exist the selected function gives an error:
Notice: Undefined index: everyoneCompose in /Applications/MAMP/... on line 22
I understand why, but how to set default values to prevent this error? I tried to check if metadata_exists and add the term meta but this doesn't work, check my code down here:
function addSelectdFieldsToCat(){
$cat_id = $_GET['tag_ID'];
if (metadata_exists('term', $cat_id, 'cat_settings' )) {
$catSettings = get_term_meta($cat_id, 'cat_settings', false);
} else {
$defaultdata = array( 'cat_settings' =>
array(
'everyoneCompose' => true,
'restrictedGroup' => true
)
);
add_term_meta($cat_id, 'cat_settings', $defaultdata, false);
}
?>
<tr class="form-field">
<th scope="row" valign="top"><label for="cat_page_title"><?php _e('Everyone can compose?'); ?></label></th>
<td>
<select name="cat_settings[everyoneCompose]">
<option value="1" <?php selected( $catSettings['everyoneCompose'], 1 ); ?>>true</option>
<option value="0" <?php selected( $catSettings['everyoneCompose'], 0 ); ?>>false, alleen admin</option>
</select>
</td>
</tr>
<tr class="form-field">
<th scope="row" valign="top"><label for="cat_page_title"><?php _e('Restricted category?'); ?></label></th>
<td>
<select name="cat_settings[restrictedGroup]">
<option value="1" <?php selected( $catSettings['restrictedGroup'], 1 ); ?>>true</option>
<option value="0" <?php selected( $catSettings['restrictedGroup'], 0 ); ?>>false</option>
</select>
</td>
</tr>
<?php
}
add_action ( 'edit_category_form_fields', 'addTitleFieldToCat');
function saveCategoryFields() {
if ( isset( $_POST['cat_settings'] ) ) {
update_term_meta($_POST['tag_ID'], 'cat_settings', $_POST['cat_settings']);
}
}
add_action ( 'edited_category', 'saveCategoryFields');