这里有一些粗略的代码给你,你可以改进查询,如果你喜欢。。。
顺便选择一下post_title
和post_status
不是必需的,但如果要确保通过foreach
环
global $wpdb;
$results = $wpdb->get_results(
"
SELECT ID, post_title, post_status
FROM {$wpdb->prefix}posts
WHERE post_status = \'publish\'
AND (post_title LIKE \'mobile\'
OR post_title LIKE \'Nokia\'
OR post_title LIKE \'Samsung\')
"
);
foreach($results as $result) {
wp_set_object_terms($result->ID, array(\'Mobile\'), \'my_taxonomy\');
}
建议阅读:
- https://codex.wordpress.org/Function_Reference/wp_set_object_terms
- https://codex.wordpress.org/Function_Reference/wp_set_post_terms根据您的评论更新:
问题是,我需要对近100个类别执行此操作。我可以为它写100个查询。问题是,我是否必须面对性能问题?
您不必为此编写100个查询,相反,您可以将流程抽象为更易于管理的内容。
如果知道要与类别关联的类别和标题,则可以通过逻辑创建如下数组,以迭代类别,从而形成SQL语句,执行查询,然后根据结果更新post对象:
set_time_limit(0); //hopefully by pass your server config
global $wpdb;
$categories = array(
//category post titles to search for
// ↓ ↓ ↓ ↓
\'mobile\' => array(\'Nokia\', \'Samsung\', \'Mobile\'),
\'tablets\' => array(\'iPad\', \'iPad mini\', \'Surface Pro 4\')
//etc...
);
$sql =<<<DOC
SELECT ID, post_title, post_status
FROM {$wpdb->prefix}posts
WHERE post_status = \'publish\'
AND (%s)
DOC;
foreach($categories as $category => $titles) {
$like = array();
foreach($titles as $title) {
$like[] = "post_title LIKE \'{$title}\'";
}
$results = $wpdb->get_results( sprintf($sql, implode(\' OR \', $like)) );
foreach($results as $result) {
wp_set_object_terms($result->ID, array($category), \'my_taxonomy\');
}
}
如果必须运行许多查询,甚至数百或数千个查询,那么应该考虑批处理/cron作业执行。如果需要不区分大小写的查询,则可以执行以下操作:
$like[] = "LOWER(post_title) LIKE LOWER(\'{$title}\')";