Hook when Post created

alexy

Active Member
88
2022
34
7,600
Hi everyone,

I have added these codes in functions.php

Code:
function assign_post_to_category($post_id, $post, $update) {
    // Run only when a new post is created, not when updated
    if (get_post_type($post_id) !== 'post') {
        return;
    }

    $post_title = get_the_title($post_id); // Get post title

    // Split the title by the dot (.)
    $title_parts = explode('.', $post_title);

    // Get the first part
    $first_word = trim($title_parts[0]);

    $category_name = trim($title_parts[0]); // Change this to your desired category name

    // Check if the category exists
    $category_id = get_term_by('name', $category_name, 'category');
    
    // If category doesn't exist, create it
    if (!$category_id) {
        $category_id = wp_insert_term($category_name, 'category');
        if (is_wp_error($category_id)) {
            return; // If there's an error, stop execution
        }
        $cat = get_term_by( 'name', $category_name, 'category' );
        $category_id = $cat->term_id;
    } else {
        $category_id = $category_id->term_id;
    }

    $extra_categories = [$category_id];
    
    // Get current categories
    $existing_categories = wp_get_post_categories($post_id);
    
    // Assign the post to the category
   // Merge and set categories
    wp_set_post_categories($post_id, array_unique(array_merge($existing_categories, $extra_categories)));
}

add_action('publish_post', 'assign_post_to_category');

What I want to achieve is that I want to assign post to new/existing category.

But it seems, code can create new category but not assign post to it.

Can you please review and share what I'm doing wrong?

Thank you
 
Back
Top