Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Automatic category creation and category as post title WordPress

  • SOLVED

Been racking my brain (and google) trying to figure this out.

What I want is for every post to automatically create a category that matches the post title. So, if I create a post titled "Look at me" I want a category to be automatically created also called "Look at me".

I think I've gotten relatively close:

$post_id = 1;
$cat = get_the_title($post_id);

// Adding category to the post
wp_set_object_terms( $post_id, array("$cat"), 'category');


Now I just need to replace the specific post ID with the current post's ID - is that possible?

Answers (3)

2010-12-06

John Cotton answers:

$post_id = 1;

$cat = get_the_title($post_id);

$id = wp_create_category( $cat );

// Adding category to the post

wp_set_object_terms( $post_id, $id, 'category');


chizet comments:

I tried using that but couldn't get it to work. Even if I could, how would I get it to work for every post and to accept the current posts' title?


John Cotton comments:

Well you wouldn't want to do this all the time surely..?

Just when you save a post presumable?

So:


add_action('save_post', 'create_new_category');

function create_new_category($post_id ) {

$cat = get_the_title($post_id);

$id = wp_create_category( $cat );

// Adding category to the post

wp_set_object_terms( $post_id, $id, 'category');

}


chizet comments:

John, this is looking great so far. Closest I've been yet.

One issue I've encountered is that I cannot assign any other categories to a post - it will only accept the code-created category - is there a way around that?


chizet comments:

Ah, solved it - added "true" as the $append argument (instead of the default "false".)

Still playing around, but again, so far this is working great. Thanks John!


John Cotton comments:

Glad it worked.

It probably needs some code in there to see whether a category of the same name exists (by default it will just create a slug of "existing-name-2"), but that really all depends on what you actually trying to achieve.


chizet comments:

Hey John, I'm going to go ahead and select your answer as the winner - it's working perfect. Thanks again!

Here is a follow-up question - is it possible to process your code only if a post does not have another category?

2010-12-06

Utkarsh Kukreti answers:

Where will you be adding the above code?


chizet comments:

Right now the above code is in functions.php

2010-12-06

Geet Purwar answers:

Yes thats entirely possible.


chizet comments:

do tell :)


Geet Purwar comments:

Simply create a function in functions.php that automatically creates/assign category to post and make this function run when post is published using action ('publish_post ').

That will do the task.