I’m still stuck on trying to attach terms to a post.
I have deactivated all plugins but Types, if I deactivate Types I can’t trigger the draft to publish event as I don’t have the custom post type in my menu anymore. The code works till the first ‘wp_get_post_terms’ arises, then it dies with no error. If somebody can tell me about another way to trigger the function (keeping the post in scope) I will deactivate Types too.
In the meantime, can somebody check this code? It comes full of comments:
function publish_post($post)
{
if('my_category' == $post->post_type) //If post belongs to my_category
{
$post_id = $post->ID;
$terms = get_post_custom_values('wpcf-my_category', $post_id);//We take the tags given in the custom post type
$terms = explode(',', $terms[0]);//They where inserted as a string so we transform them in to an array to iterate
if(is_array($terms))//We check that it is a real array (becaming really paranoid)
{
for($x = 0; $x < count($terms); $x++)//Loop array elements
{
$term_id = term_exists( $terms[$x]);//Lets see if the terms already exist as terms
if ($term_id !== 0 && $term_id !== null)//If term exists we will only attach it to the post
{
$term_list = wp_get_post_terms($post_id, 'my_category', array("fields" => "term_id"));//Let's check if they are attached already
if(!in_array($term_id, $term_list))//If they are not attached we do
{
$term_taxonomy_ids = wp_set_post_categories((int)$post_id, (int)$term_id, true);//Here comes the nightmare
if ( is_wp_error( $term_taxonomy_ids ) )
{
echo 'Categories have been added';// There was an error somewhere and the terms couldn't be set.
}
else
{
echo 'Error adding categories';// There was no error, but the terms haven't ben set
}
}
}
else//If term doesn't exists we will create them and get their ID back
{
$term_object = wp_insert_term(
$terms[$x], // the term
'my_category', // the taxonomy
array(
'description'=> '',
'slug' => slugify($terms[$x])
)
);//After inserting with wp_insert_term we should have an objcet back
$term_id = $term_object['term_id'];//From this object we get the ID
$term_taxonomy_ids = wp_set_object_terms((int)$post_id, (int)$term_id, 'my_category', true);//We set the terms
if ( is_wp_error( $term_taxonomy_ids ) )
{
echo 'Categories have been added';// There was an error somewhere and the terms couldn't be set.
}
else
{
echo 'Error adding categories';// Success! The post's categories were set.
}
}
}
}
}
}