WordPress将在保存到post meta时序列化数组。存储在键下的数据_employer_socials
在您的示例中看起来like this:
Array
(
[0] => Array
(
[network] => facebook
[url] => #
)
[1] => Array
(
[network] => twitter
[url] => #
)
[2] => Array
(
[network] => linkedin
[url] => #
)
[3] => Array
(
[network] => instagram
[url] => #
)
)
当您获得meta时,WP将为您取消序列化,如下所示:
$employer_socials = get_post_meta( get_the_ID(), \'_employer_socials\', true );
然后,您可以将数据作为常规数组处理。保存阵列时,WP将为您序列化它。以下是一些可以作为起点使用的基本函数:
/**
* Updates an existing network, or adds a new one if it does not exist.
*
* @param int $post_id The Post ID to be updated.
* @param string $network The name of the network to check.
*
* @return bool True if an update was made, false otherwise.
*/
function wpse_update_employee_social( $post_id, $network, $url ) {
$employer_socials = get_post_meta( $post_id, \'_employer_socials\', true );
// Update.
if ( wpse_has_employer_social( $post_id, $network ) ) {
foreach ( $employer_socials as $key => $employer_social ) {
if ( $employer_social[\'network\'] === $network ) {
$employer_socials[ $key ][\'url\'] = $url;
update_post_meta( $post_id, \'_employer_socials\', $employer_socials );
return true;
}
}
} else {
// Add.
$employer_socials[] = [
\'network\' => $network,
\'url\' => $url,
];
update_post_meta( $post_id, \'_employer_socials\', $employer_socials );
return true;
}
// Nothing was updated.
return false;
}
/**
* Checks if a given network exists.
*
* @param int $post_id The Post ID to be updated.
* @param string $network The name of the network to check.
*
* @return bool True if the network exits, false otherwise.
*/
function wpse_has_employer_social( $post_id, $network ) {
$employer_socials = get_post_meta( $post_id, \'_employer_socials\', true );
foreach ( $employer_socials as $employer_social ) {
if ( $employer_social[\'network\'] === $network ) {
return true;
}
}
return false;
}
添加新员工社交的示例:
wpse_update_employee_social( 5302, \'wpse\', \'https://wordpress.stackexchange.com/users/208214/user1669296\' );
更新员工社交网站的示例:
wpse_update_employee_social( 5302, \'facebook\', \'#1234\' );