场景:
我有1000个帖子有“未分类”类别,我想从所有帖子中删除“未分类”,并为这些帖子设置不同的类别。
换句话说 - 将所有未分类的帖子转移到另一个类别,一举一动。
我是否可以批量执行此操作而无需单独浏览每个帖子?
您正在寻找的是WordPress批量编辑器。
将所有帖子添加到“新类别”后,您需要删除“未分类”类别。去做这个:
删除“未分类”类别后,它会将其从您的所有帖子中删除。
如果您有一些想要保留在“未分类”的帖子,则创建一个名为“temp”的新类别,并将您要保留的所有帖子分配到该类别。删除“Uncategorized”后再次创建它并将“temp”中的帖子分配回该类别。
未分类的类别的ID为1
。我们的工作流程是什么,
使用wp_set_object_terms()
删除并设置我们的新tems
下面的代码需要PHP 5.4+,任何更改都是不可逆的,因此请先备份数据库
$args = [
'nopaging' => true, // Gets all posts
'cat' => 1, // Only gets posts assigned to category 1 which is the uncategorized category
'fields' => 'ids', // Only get post ID's, make query up 1000 times faster on huge databases
];
$q = get_posts( $args );
if ( $q ) {
foreach ( $q as $v ) {
// Get all the post categories
$categories = get_the_category( $v );
$category_ids = [];
foreach ( $categories as $category ) {
// Replace all uncategorized category instances with our new category id and build new array
if ( $category->term_id == 1 ) {
$category_ids[] = (int) 21; // REPLACE WITH THE CORRECT NEW CATEGORY ID
} else {
$category_ids[] = (int) $category->term_id;
}
}
// Set our new categories to the post
if ( $category_ids ) // Unnecessary check for categories, but just in case should something fail
wp_set_object_terms( $v, $category_ids, 'category' );
}
}
注意,我们没有更改过$post
全局或设置postdata,所以我们不需要调用wp_reset_postdata()
:-)
Wordpress存储wp_term_relationships
表中类别和帖子之间的父/子关系,here记录了该表。正如@Pieter Goosen所指出的那样,“未分类”类别的ID为1
。因此,您可以备份SQL数据库,然后使用SQL命令行客户端连接到它(sudo mysql wordpress
适用于我),并运行此SQL命令:
delete from wp_term_relationships where term_taxonomy_id = 1;
正如您所发现的那样,批量编辑器只允许将类别添加到多个帖子 - 从多个帖子中删除类别是不可能的。我找到的最佳选择是临时安装此插件https://wordpress.org/plugins/bulk-remove-posts-from-category/(在WP存储库中),它增加了使用相同的批量编辑方法从多个帖子中删除类别的功能。它只是在类别列表下添加了一个额外的“删除”复选框。
您可以将其添加到主题的functions.php文件中,然后刷新站点上的任何页面,然后删除该功能。
使用风险自负,先备份数据库!这上面没有UNDO按钮。
<?php
$args = array(
'posts_per_page' => -1
);
$myposts = get_posts( $args );
foreach ( $myposts as $post ) :
setup_postdata( $post );
$categories = get_the_category();
$catcount = count($categories);
$postid = $post->ID;
$catlist = array();
//Building a list of categories for each post and EXCLUDING "uncategorized"
foreach( $categories as $category ) {
if($category->name == 'Uncategorized') {
continue;
}
$catlist[] = $category->term_id;
}
// If there's just one category, and that category is "Uncategorized", move the category to one of your choosing
if($catcount == 1 && $categories[0]->name == "Uncategorized") {
// This is the category ID that you want to move uncategorized posts to
$catlist = array(189);
}
wp_set_object_terms( $postid, $catlist, 'category' );
endforeach;
wp_reset_postdata();
?>