0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Really Simple CSV Importerで登録したカスタムフィールドをCustom Field Suiteに反映する

Posted at

Really Simple CSV Importerで登録したカスタムフィールドはそのままでは
プラグインが認識しません。
Advanced Custom field や Smart Custom Fieldsには対応方法が見つかりましたが、
Custom Field Suiteでは見つけれず。
データベースを除くと、wp_cfs_valuesにメタデータを登録されてないと、認識できないようです。
幸いデータ登録用のAPIがあったので、それを利用します。
https://mgibbs189.github.io/custom-field-suite/api.html

CSVインポート時のフックはpost id が確定させる必要があるので、
really_simple_csv_importer_post_saved
を使用します。

以下コード

add_filter( 'really_simple_csv_importer_post_saved', function ($post) {
	global $wpdb;
	
	try {
		// CFSで登録したメタデータの項目を取得
		$cflds = CFS()->find_fields( [
			'post_id' => $post->ID,
		] );
		$metaKeys = array_column($cflds, 'name');
		$metaKeysPlaceHolder = implode(', ', array_fill(0, count($metaKeys), '%s'));
		// CFS登録にメタデータ取得
		$curMeta = $wpdb->get_results(
			call_user_func_array([$wpdb, 'prepare'], array_merge([
				"SELECT * FROM $wpdb->postmeta WHERE post_id = %d AND meta_key IN ({$metaKeysPlaceHolder})"
			], [$post->ID], $metaKeys))
		);
		// 標準メタデータは不要なので削除
		$wpdb->query(
			call_user_func_array([$wpdb, 'prepare'], array_merge([
				"DELETE FROM $wpdb->postmeta WHERE post_id = %d AND meta_key IN ({$metaKeysPlaceHolder})"
			], [$post->ID], $metaKeys))
		);
		// CFSでメタデータ登録
		CFS()->api->save_fields(array_column($curMeta, 'meta_value', 'meta_key'), ['ID' => $post->ID]);
	} catch ( Exception $e ) {
		// ログ出しとか
	}
}, 10 );
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?