Hello there,
To achieve this, you’ll need to create a custom user profile field for selecting a category and then use that field to programmatically set the category of posts created by the user.
You can use the user_contactmethods
hook to add a custom field to the user profile. Here’s how you can do that:
// Add custom user profile field
function add_user_category_field($user) {
$categories = get_categories();
$selected_category = get_user_meta($user->ID, 'user_category', true);
?>
<h3><?php _e("User Category", "blank"); ?></h3>
<table class="form-table">
<tr>
<th><label for="user_category"><?php _e("Category"); ?></label></th>
<td>
<select name="user_category" id="user_category">
<option value="">Select a category</option>
<?php foreach ($categories as $category) : ?>
<option value="<?php echo esc_attr($category->term_id); ?>" <?php selected($selected_category, $category->term_id); ?>>
<?php echo esc_html($category->name); ?>
</option>
<?php endforeach; ?>
</select>
<br /><span class="description"><?php _e("Select a category for this user."); ?></span>
</td>
</tr>
</table>
<?php
}
add_action('show_user_profile', 'add_user_category_field');
add_action('edit_user_profile', 'add_user_category_field');
// Save the custom user profile field
function save_user_category_field($user_id) {
if (!current_user_can('edit_user', $user_id)) {
return false;
}
update_user_meta($user_id, 'user_category', $_POST['user_category']);
}
add_action('personal_options_update', 'save_user_category_field');
add_action('edit_user_profile_update', 'save_user_category_field');
Next, you need to set the category of a post programmatically based on the user profile. You can use the save_post
hook for this:
function set_post_category_based_on_user($post_id) {
// Check if it's a valid post and not an autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
// Check if it's a post and not a revision
if (get_post_type($post_id) != 'post') {
return;
}
// Get the user ID of the author
$author_id = get_post_field('post_author', $post_id);
// Get the category assigned to the user
$user_category = get_user_meta($author_id, 'user_category', true);
if ($user_category) {
// Set the post's category
wp_set_post_categories($post_id, array($user_category));
}
}
add_action('save_post', 'set_post_category_based_on_user');
You will need to add this code to your theme functions.php file or via Code Snippet plugin. Give it a try but beware, adding code like this can cause a fatal error on your site if something is off, make sure you can undo the code change if things go south.
Summary
- Add a custom field to the user profile to select a category from existing categories.
- Save the selected category when the user profile is updated.
- Automatically set the category of new posts based on the user’s selected category when the post is saved.
This approach should provide a clean solution without relying on complex plugins.
Kind Regards.