How to Automatically Assign Posts to Categories Based on Titles in WordPress
Managing a website with numerous categories can be a daunting task, especially if you frequently publish new content. However, WordPress offers a powerful way to streamline this process: automatically assigning posts to categories based on their titles. In this article, we’ll walk you through how to implement this feature on your WordPress site.
How to Set It Up
To automatically assign posts to categories based on their titles, you can use custom code. Here’s how to do it:
Step 1: Add the Code to Your Theme’s Functions File
You can add the following code snippet to your theme’s functions.php
file or use a custom plugin to avoid issues when updating your theme.
<?php
function assign_additional_categories_based_on_title($post_id) {
// Ensure this runs only when a post is published
if (get_post_status($post_id) !== 'publish') {
return;
}
// Get the post title
$post_title = get_the_title($post_id);
if (!$post_title) {
return;
}
// Get all existing categories
$categories = get_categories(array('hide_empty' => false));
$categories_to_add = array();
// Check if any category name matches a word in the post title
foreach ($categories as $category) {
if (stripos($post_title, $category->name) !== false) {
$categories_to_add[] = $category->term_id;
}
}
// If matches are found, add them to the post's categories
if (!empty($categories_to_add)) {
wp_set_post_categories($post_id, $categories_to_add, true); // 'true' ensures adding new categories without overwriting existing ones
}
}
// Hook into the 'save_post' action
add_action('save_post', 'assign_additional_categories_based_on_title');
Step 2: Test the Functionality
- Create or edit a post.
- Use a title that matches one or more of your category names.
- Save or publish the post.
The post will automatically be assigned to the matching category or categories.