以下是有效的代码:
function untag_posts($post_ids, $tags) {
global $wpdb;
if(! is_array($post_ids) ) {
$post_ids = array($post_ids);
}
$in_post_ids = implode("\',\'", $post_ids);
if(! is_array($tags) ) {
$tags = array($tags);
}
$in_tag_names = "\'" . implode("\',\'", $tags) . "\'";
$query = "SELECT tt.term_taxonomy_id " .
" from $wpdb->terms as t " .
" JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id " .
" JOIN $wpdb->term_relationships as tr on tr.term_taxonomy_id = tt.term_taxonomy_id " .
" where t.name in ($in_tag_names) " .
" AND (tr.object_id in ($in_post_ids)) ";
$tt_ids = $wpdb->get_col($query); // TODO: correct function?
$in_tt_ids = implode("\',\'", $tt_ids);
$delete_query = "DELETE FROM $wpdb->term_relationships where object_id in ($in_post_ids) and term_taxonomy_id in ($in_tt_ids)";
$myrows = $wpdb->get_results( $delete_query );
}
下面是一个可行的备用代码:
function untag_post($post_ids, $tags) {
global $wpdb;
if(! is_array($post_ids) ) {
$post_ids = array($post_ids);
}
if(! is_array($tags) ) {
$tags = array($tags);
}
foreach($post_ids as $post_id) {
$terms = wp_get_object_terms($post_id, \'post_tag\');
$newterms = array();
foreach($terms as $term) {
if ( !in_array($term->name,$tags) ) { //$term will be a wordpress Term object.
$newterms[] = $term;
}
}
wp_set_object_terms($post_id, $newterms, \'post_tag\', FALSE);
}
}
下面是我在wordpress测试环境中使用的测试数据(http://codex.wordpress.org/Automated_Testing)测试功能:
function test_untag_post() {
function untag_post($post_ids, $tags) {
global $wpdb;
if(! is_array($post_ids) ) {
$post_ids = array($post_ids);
}
if(! is_array($tags) ) {
$tags = array($tags);
}
foreach($post_ids as $post_id) {
$terms = wp_get_object_terms($post_id, \'post_tag\');
$newterms = array();
foreach($terms as $term) {
if ( !in_array($term->name,$tags) ) { //$term will be a wordpress Term object.
$newterms[] = $term;
}
}
wp_set_object_terms($post_id, $newterms, \'post_tag\', FALSE);
}
}
$post = array();
$post[\'post_content\'] = "Here is some content.";
$post[\'post_excert\'] = "Quick excerpt.";
$post[\'post_title\'] = "Test Post";
$post[\'post_name\'] = "test-post";
$post[\'post_type\'] = "post";
$post_id = wp_insert_post($post);
wp_add_post_tags($post_id, \'test-tag\');
$terms = wp_get_object_terms($post_id, \'post_tag\');
$this->assertEquals(\'test-tag\', $terms[0]->name);
untag_post($post_id, \'test-tag\');
$terms = wp_get_object_terms($post_id, \'post_tag\');
$this->assertEmpty($terms);
}
编辑:下面(这是我以前的答案)
IS WRONG我之前的回答所允许的只是一种删除所有贴子标签的方法。但我正在寻找一种只删除特定帖子标签的方法。
功能wp_delete_object_term_relationships
(wp-includes/taxonomy.php
第1662行)是执行此操作的低级别函数。然而
如果需要的话,它不会自动将某些东西归类(这可能不是问题)
我还没有测试过这个
我觉得使用wordpress文档网站上没有提到的用于公共用途的低级功能有点不舒服。
所以也许有更好的方法。