tags:

views:

28

answers:

3

Hey Guys,

I've got a function to add a tag by post ID, but now I would like to delete all the current tags for that ID before adding my new tags?

Does anyone know a built in function or wordpress query to do this?

-Hudson

+1  A: 

Should help you get there:

Wordpress API: Add / Remove Tags on Posts

I found this function: wp_delete_term See if it helps you...

Leniel Macaferi
I found that one, and thats where I got my add tags script, but I do not read or understand a delete all tags function in that resource.
atwellpub
+2  A: 

If you can access the database directly (PhpMyAdmin), the quickest way is a SQL request.

Look at the database schema in the codex :

DELETE FROM wp_term_relationships
WHERE wp_term_relationships.object_id = 'yourPostId'
AND wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
AND wp_term_taxonomy.taxonomy = 'post_tag';

WARNING : obviously, modifying directly the database is dangerous. Be careful doing that.

Benoit Courtine
I believe this might also delete category associations.
atwellpub
Yes it does. To delete only tags, this code must be precised (by a condition on wp_term_taxonomy but since I haven't a database, I can't say what condition right now :/)
Benoit Courtine
I looked at a WP database and edited my response. The new SQL request only delete the post tags.
Benoit Courtine
A: 

I pieced this together. Its pure database work, because I believe there is no quick function to delete a tag via ID, (but I am still not 100% certain).

//define array of tags
$tags = array("new tag","new tag 2");     
//define post ID
$val = 254;

 //delete tags associated to post id
$query = "SELECT * FROM ".$table_prefix."term_relationships tr JOIN ".$table_prefix."term_taxonomy tt ON tr.term_taxonomy_id=tt.term_taxonomy_id WHERE tr.object_id='$val' AND tt.taxonomy='post_tag'";
$result = mysql_query($query);
if (!$result){echo $query; echo mysql_error();}

while ($arr = mysql_fetch_array($result))
{
        $tid = $arr['term_taxonomy_id'];
        $query2 = "DELETE FROM ".$table_prefix."term_relationships WHERE term_taxonomy_id='$tid'";
        $result2 = mysql_query($query2);
        if (!$result2){echo $query2; echo mysql_error();}
}


//add tags to post id           
wp_add_post_tags($val,$tags);
atwellpub
Yes, there is... look at my updated answer.
Leniel Macaferi