Han*_*com 2 wordpress categories
场景:
我有1000个帖子有"未分类"类别,我想从所有帖子中删除"未分类",并为这些帖子设置不同的类别.
换句话说 - 将所有未分类的帖子转移到另一个类别,一举一动.
我是否可以批量执行此操作而无需单独浏览每个帖子?
您正在寻找的是WordPress批量编辑器.
转到帖子>类别>未分类
单击右上角的"屏幕选项"选项卡,然后将"每页项目数:"更改为1000.(如果您使用的是非常慢的服务器,则可以考虑一次减少)
现在选择页面上的所有项目,然后单击全选上方的"批量操作"下拉列表,然后选择"编辑"选项.
点击申请
在批量编辑器中,单击要更改所有帖子的"新类别"并点击更新.
将所有帖子添加到"新类别"后,您需要删除"未分类"类别.去做这个:
删除"未分类"类别后,它会将其从您的所有帖子中删除.
如果您有一些想要保留在"未分类"的帖子,则创建一个名为"temp"的新类别,并将您要保留的所有帖子分配到该类别.删除"Uncategorized"后再次创建它并将"temp"中的帖子分配回该类别.
小智 6
正如您所发现的,批量编辑器只允许将类别添加到多个帖子 - 无法从多个帖子中删除类别。我发现的最佳选择是临时安装此插件https://wordpress.org/plugins/bulk-remove-posts-from-category/(在 WP 存储库中),它增加了使用从多个帖子中删除类别的能力相同的批量编辑方法。它只是在类别列表下添加了一个额外的“删除”复选框。
未分类的类别的ID为1.我们的工作流程是什么,
获取分配给未分类类别的所有帖子.
我们只会获得帖子ID,这将使我们的查询在拥有数千个帖子的网站上的速度提高1000倍.这也有助于我们的查询不会超时或达到最大内存致命错误.
使用wp_set_object_terms()删除,并设置我们新的电信设备制造商
下面的代码需要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' );
}
}
Run Code Online (Sandbox Code Playgroud)
注意,我们没有更改$post全局或设置postdata,所以我们不需要调用wp_reset_postdata():-)
Han*_*com -1
您可以将其添加到主题的functions.php 文件中,然后刷新网站上的任何页面一次,然后删除该函数。
使用风险自负,请先备份数据库!这里没有撤消按钮。
<?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();
?>
Run Code Online (Sandbox Code Playgroud)