WordPress REST API提供了对WordPress内容的编程访问,包括文章、页面、评论、分类和自定义字段(元数据)。元数据在API响应中通常以序列化的形式返回,这在使用时需要特别注意。
WordPress元数据在REST API响应中默认是序列化的字符串格式,这是因为:
// 安装php-serialized模块
// npm install php-serialized --save
angular.module('myApp').controller('WPController', function($http, $scope) {
$http.get('https://your-wordpress-site.com/wp-json/wp/v2/posts/123')
.then(function(response) {
var serialized = response.data.meta.your_meta_key;
// 使用php-serialized库反序列化
var unserialized = require('php-serialized').unserialize(serialized);
$scope.metaData = unserialized;
});
});
安装并激活"WP REST API Meta Endpoints"插件,它会自动处理元数据的序列化问题。
// 在主题的functions.php中添加
add_action('rest_api_init', function() {
register_rest_field('post', 'unserialized_meta', array(
'get_callback' => function($object) {
$meta = get_post_meta($object['id']);
foreach ($meta as $key => $value) {
if (is_serialized($value[0])) {
$meta[$key] = unserialize($value[0]);
} else {
$meta[$key] = $value[0];
}
}
return $meta;
},
'schema' => null,
));
});
然后在AngularJS中直接访问unserialized_meta
字段。
在存储元数据时,使用json_encode
和json_decode
替代PHP的序列化函数:
// 存储时
update_post_meta($post_id, 'meta_key', json_encode($data));
// 获取时
$data = json_decode(get_post_meta($post_id, 'meta_key', true));
这种技术适用于:
没有搜到相关的文章