我一直在努力从json数据导入帖子。问题是wp_insert_post()
正在添加帖子的多个版本。我之前是通过检查标题是否存在来检查帖子是否存在,但是有几个帖子需要导入,它们的标题相同,但内容不同。
function get_all_cpt_ids() {
global $wpdb;
$mids = $wpdb->get_results( "SELECT ID FROM tablename.subsite_4_posts WHERE post_type=\'thing\'", OBJECT );
foreach ( $mids as $key => $value ) {
$thing_ids[] = $value->ID;
}
return $thing_ids;
}
function mysite_import_json() {
$json_feed = \'http://local.mysite.com/wp-content/test.json\';
$json = file_get_contents( $json_feed );
$objs = json_decode( $json, true );
$wp_error = true;
$id_arr = [];
foreach ( $objs as $obj ) {
$id_arr = get_all_cpt_ids();
$id = $obj[\'nid\'];
$title = $obj[\'title\'];
$meta1 = $obj[\'name\'];
$d = new DateTime();
$d->setTimestamp( $obj[\'created\'] );
$date_created = $d->format( \'Y-m-d H:i:s\' );
$post_meta = array(
\'meta_1\' => $meta1,
);
$post_data = array(
\'import_id\' => $id,
\'post_title\' => $title,
\'post_date\' => $date_created,
\'post_status\' => \'publish\',
\'post_type\' => \'thing\',
\'meta_input\' => $post_meta,
);
if ( ! in_array( $id_arr, $id, true ) ) {
$post_id = wp_insert_post( $post_data, $wp_error );
foreach ( $field_meta as $key => $value ) {
update_post_meta( $post_id, $key, $value );
}
}
}
}
add_action( \'after_setup_theme\', \'mysite_import_json\' );
顺便说一句,我是在本地完成这项工作的,所以我不担心查询数据库时的安全性。
我还通过在函数运行后添加一个标志作为选项,将其设置为只运行一次,所以我真的不明白为什么wp_insert_post()
每运行一次以上$obj
在foreach
环