我使用了适用于wordpress的csv导入插件的改编版本。它导入csv以创建和更新帖子。要更新现有帖子,我添加了一个按标题查找帖子ID的编辑,如果它存在则会覆盖,否则会创建一个新帖子。
问题是它似乎不太可靠!如果我多次导入相同的csv,它会覆盖大部分csv,但我会得到一些重复。有什么方法可以让我更可靠,还是有另外一种方法可以处理重复的帖子?
此处创建帖子的主要功能
function create_post($data, $options) {
extract($options);
//edit 1 added here
global $wpdb;
//end
$data = array_merge($this->defaults, $data);
$type = $data['csv_post_type'] ? $data['csv_post_type'] : 'post';
$valid_type = (function_exists('post_type_exists') &&
post_type_exists($type)) || in_array($type, array('post', 'page'));
if (!$valid_type) {
$this->log['error']["type-{$type}"] = sprintf(
'Unknown post type "%s".', $type);
}
$new_post = array(
'post_title' => convert_chars($data['csv_post_title']),
'post_content' => wpautop(convert_chars($data['csv_post_post'])),
'post_status' => $opt_draft,
'post_type' => $type,
'post_date' => $this->parse_date($data['csv_post_date']),
'post_excerpt' => convert_chars($data['csv_post_excerpt']),
'post_name' => $data['csv_post_slug'],
'post_author' => $this->get_auth_id($data['csv_post_author']),
'tax_input' => $this->get_taxonomies($data),
'post_parent' => $data['csv_post_parent'],
);
// edit 2 here
$new_post['ID'] = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = '" . $data['csv_post_title'] . "'" );
// ends
// pages don't have tags or categories
if ('page' !== $type) {
$new_post['tags_input'] = $data['csv_post_tags'];
// Setup categories before inserting
$cats = $this->create_or_get_categories($data, $opt_cat);
$new_post['post_category'] = $cats['post'];
}
// edit 3
if(!empty($new_post['ID'])) {
$id = wp_update_post($new_post);
} else {
$id = wp_insert_post($new_post);
}
// ends
if ('page' !== $type && !$id) {
// cleanup new categories on failure
foreach ($cats['cleanup'] as $c) {
wp_delete_term($c, 'category');
}
}
return $id;
}
感谢
答案 0 :(得分:0)
固定!我使用了内置的wordpress函数get_page_by_title
。这是我用来定位正确帖子的代码。
if (!get_page_by_title( $bpp_title, 'OBJECT', 'publications')) {
$id = wp_insert_post($new_post);
} else {
$bpp_page = get_page_by_title( $bpp_title, 'OBJECT', 'publications');
$new_post['ID'] = $bpp_page->ID;
$id = wp_update_post($new_post);
}