问题
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:
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.
回答2:
Should help you get there:
Wordpress API: Add / Remove Tags on Posts
I found this function: wp_delete_term See if it helps you...
回答3:
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);
来源:https://stackoverflow.com/questions/3356380/wordpress-delete-all-tags-by-post-id