Last active
September 5, 2023 19:44
-
-
Save takunagai/790925b6ececb95cc558febf59234225 to your computer and use it in GitHub Desktop.
[WordPress: Data Serialization and Database I/O] WordPress データのシリアル化とデータベースへの入出力 #WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* WordPress データのシリアル化とデータベースへの入出力 | |
* @ref: https://wporz.com/wordpress-serialize/ | |
*/ | |
/** | |
* 複数のデータを配列にセットしシリアル化、wp_options テーブルに保存 | |
*/ | |
$update[] = $data1; | |
$update[] = $data2; | |
$update[] = $data3; | |
$update[] = $data4; | |
$update_serialize = maybe_serialize( $update ); | |
update_option( 'my_data', $update_serialize ); | |
/** | |
* wp_options テーブルにあるシリアル化データを取得し、アンシリアル化 | |
*/ | |
$get_data = get_option( 'my_data' ); | |
$data_unserialize = maybe_unserialize( $get_data ); | |
foreach ( $data_unserialize as $value ) { | |
// 処理 | |
} | |
/** | |
* シリアル化したデータから一部を削除 (配列に変換してから処理) | |
*/ | |
$get_data = get_option( 'my_data' ); | |
$data_unserialize = maybe_unserialize( $get_data ); | |
// $data に削除したいデータ(値を指定) | |
// 配列のキーが分かっているなら unset でも可 | |
$result_data = array_diff( $data_unserialize, array( $data ) ); | |
// キーが歯抜け状態なのでトリミング | |
$new_data = array_values( $result_data ); | |
$data_serialize = maybe_serialize( $new_data ); | |
update_option( 'my_data', $data_serialize ); | |
/** | |
* シリアル化したデータに、データを追加 | |
*/ | |
$get_data = get_option( 'my_data' ); | |
$data_unserialize = maybe_unserialize( $get_data ); | |
// 配列の末尾に追加 | |
$data_unserialize[] = $add_data; | |
// 配列にデータが重複しないようユニークチェック | |
$new_data = array_unique( $data_unserialize ); | |
$data_serialize = maybe_serialize( $new_data ); | |
update_option( 'my_data', $data_serialize ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment