我不建议您在暴露于各种数据损坏时使用直接SQL方法。
最好的方法是创建一个只运行一次的PHP函数并执行该任务。您可能会遇到一些超时问题,但可以通过临时设置非常高的PHP超时值来克服这些问题。
首先,您应该确保在WP admin中正确创建了新类别。然后在数组中记住它们的ID。
为了让您开始,这是我将使用的功能,连接到WP admin dashboard中,因此它只在您转到该页面时启动。
function wp1234_attach_posts_to_new_categories() {
$categories_mapping = array(
\'targetword1\' => \'101\', //this is a category ID
\'targetword2\' => \'102\', //this is another category ID
\'targetword3\' => \'103\', //this is yet another category ID
);
// Grab all the posts and cycle through them
$args = array(
\'post_type\' => \'post\',
\'posts_per_page\' => -1,
\'post_status\' => \'publish\',
\'suppress_filters\' => true,
\'ignore_sticky_posts\' => true,
\'no_found_rows\' => true,
\'cache_results\' => false, // there is no need to cache this
);
$new_query = new WP_Query();
foreach ( $new_query->query( $args ) as $post ) {
if ( ! empty( $post->post_content ) ) {
foreach ( $categories_mapping as $word => $category_id ) {
if ( false !== strpos( $post->post_content, $word ) ) {
// We have found the word in the content
// Attach the post to the category, by appending to existing categories - the last parameter
wp_set_post_categories( $post->ID, array( absint( $category_id ) ), true );
// We will stop at the first found word
break;
}
}
}
}
// Leave a sign that we have done something
print( PHP_EOL . \'### ATTACHED POSTS TO CATEGORIES ###\' . PHP_EOL );
}
// This action gets run only on the WP admin dashboard page
add_action( \'wp_dashboard_setup\', \'wp1234_attach_posts_to_new_categories\' );
完成后,移除
add_action
至少这样你就不会重击你的网站了。
如果有帮助,请告诉我。