我是 WordPress 粉丝,大部分时间都在使用 高级自定义字段插件。 我有两个自定义帖子类型,它们与 ACF 插件中的 relationship 字段链接在一起。我目前正在开发移动版本,其中使用 Plugin JSON API 和 AngularJS。它工作得很好,而不是关系字段值。
我在带有 1 个链接资源的 JSON 文件中看到了这一点:
["a:1:{i:0;s:3:"163";}", "a:1:{i:0;s:3:"163";}"]
["a:2:{i:0;s:3:"261";i:1;s:2:"56";}", "a:2:{i:0;s:3:"261";i:1;s:2:"56";}"]
"custom_fields": {
"main_statement": [
"",
""
],
"type_of_presentation": [
"keynote",
"keynote"
],
"room": [
"no_room",
"no_room"
],
"skill_level": [
"null",
"null"
],
"start_date": [
"1412084700",
"1412084700"
],
"end_date": [
"1412087700",
"1412087700"
],
"speakers": [
"a:1:{i:0;s:3:\"154\";}",
"a:1:{i:0;s:3:\"154\";}"
]
}
非常感谢!
致以诚挚的问候
序列化数组。
所以你基本上只需要使用
unserialize() php 函数。
我测试了它,它确实提取了数组中的 ID
json_decode() 不适用于非 JSON 数据。
WP REST API v2,这是最终将包含在 WordPress 核心中的 API。
为了回答您的问题,问题是您正在使用的 JSON API 插件显示的数据与存储在 MySQL 数据库中的数据完全相同。为了将 PHP 对象存储到数据库中,它们必须被序列化。a:1:{i:0;s:3:\"154\";}
是 PHP 数组
array("154")
的序列化表示。我们需要做的是对响应中的每个自定义字段值应用
maybe_unserialize。幸运的是,JSON API 插件作者在插件中包含了一个 json_api_import_wp_post
操作,该操作在响应帖子对象形成后立即运行。您可以将下面的代码片段添加到主题的functions.php 或自定义插件(如果您有用于该项目的插件)。
/**
* Apply maybe_unserialize on all post's custom_fields in a JSON API response.
*
* @param JSON_API_Post $api_post The result of JSON_API_Post->import_wp_object
* @param WP_Post $wp_post WP_Post that was converted
* @return JSON_API_Post
*/
function namespace_unserialize_json_api_import_wp_post($api_post, $wp_post) {
// Check if there are custom_fields
if( isset($api_post->custom_fields) ) {
// Loop them all through
foreach($api_post->custom_fields as $key => $custom_field) {
// All of the custom_field values are arrays, so apply maybe_unserialize
// to all the array items with maybe_unserialize and set it as the key
$api_post->custom_fields->$key = array_map('maybe_unserialize', $custom_field);
}
}
return $api_post;
}
// Add namespace_unserialize_json_api_import_wp_post to the json_api_import_wp_post action hook.
add_action('json_api_import_wp_post', 'namespace_unserialize_json_api_import_wp_post', 10, 2);
注意:将“namespace_”替换为更适合您项目的内容。