在Wordpress 5.1.1中,我有一个名为“食品”的自定义帖子类型。它由一个标题和图像画廊块组成。
在自定义Wordpress rest端点中,我希望从图库获取图像urls。
在发送数据之前,我循环通过post,并将ACF添加到post中,并认为相同的方法会工作。
已经尝试过以下Wordpress函数:
get_post_gallery()
get_post_gallery_images()我能理解的块的更新方法。
get_post_galleries()
get_post_galleries_images()这是我的邮政回路。ACF方法起作用。
function api_get_all_posts() {
$args = array(
'post_type' => array(
'food',
),
'post_status' => 'publish',
'order' => 'DESC',
'post_per_page' => '5'
);
$the_query = new WP_Query($args);
$posts = $the_query->posts;
if ( empty( $posts ) ) {
return new WP_Error(array( 'status' => 404 ) );
} else {
foreach ($posts as $key => $post) {
$ID = $post->ID;
//Set AFC
$posts[$key]->acf = get_fields($ID);
//Set images
$posts[$key]->images = get_post_galleries_images( $ID );
}
}
return rest_ensure_response($posts);
}这是我发送给前端的JSON:
[
{
"ID": 44,
"post_author": "0",
"post_date": "2019-04-08 22:21:48",
"post_date_gmt": "2019-04-08 22:21:48",
"post_content": "<!-- wp:gallery {\"ids\": [\"88\",\"87\",\"86\",91],\"columns\":4} -->\n<ul class=\"wp-block-gallery columns-4 is-cropped\"><li class=\"blocks-gallery-item\"><figure><img src=\"http://localhost/gwp/wp-content/uploads/2019/04/food-3-823x1024.jpg\" alt=\"\" data-id=\"88\" data-link=\"http://localhost/gwp/food-3/\" class=\"wp- image-88\"/></figure></li></ul>\n<!-- /wp:gallery -->",
"post_title": "Food test",
"post_excerpt": "",
"post_status": "publish",
"comment_status": "closed",
"ping_status": "closed",
"post_password": "",
"post_name": "fodd-test",
"to_ping": "",
"pinged": "",
"post_modified": "2019-04-17 08:33:39",
"post_modified_gmt": "2019-04-17 08:33:39",
"post_content_filtered": "",
"post_parent": 0,
"guid": "http://localhost/gwp/?post_type=food&p=44",
"menu_order": 0,
"post_type": "food",
"post_mime_type": "",
"comment_count": "0",
"filter": "raw",
"acf": {
"post_template": "food"
},
"images": []
}
]我可以通过观看'post_content‘看到图片在那里,但它找不到画廊。它总是在“图像”中给我一个空数组?
有什么建议吗?谢谢你的阅读。
发布于 2019-04-24 03:06:35
这些函数只适用于经典编辑器中使用的(旧的) [gallery]短代码,因此它们不会返回任何与图库块(即<!-- wp:gallery ... -->...<!-- /wp:gallery -->)有关的内容:
get_post_gallery()get_post_gallery_images()get_post_galleries()get_post_galleries_images()我不知道库块的等效函数;但是,您可以使用这个自定义函数来获得类似于get_post_galleries_images()返回的内容:(将其添加到主题functions.php文件中)
function get_post_block_galleries_images( $post_id ) {
$content = get_post_field( 'post_content', $post_id );
$srcs = [];
$i = -1;
foreach ( parse_blocks( $content ) as $block ) {
if ( 'core/gallery' === $block['blockName'] ) {
$i++;
$srcs[ $i ] = [];
preg_match_all( '#src=([\'"])(.+?)\1#is', $block['innerHTML'], $src, PREG_SET_ORDER );
if ( ! empty( $src ) ) {
foreach ( $src as $s ) {
$srcs[ $i ][] = $s[2];
}
}
}
}
return $srcs;
}然后在您的代码中,只需替换如下:
$posts[$key]->images = get_post_galleries_images( $ID );通过以下方式:
$posts[$key]->images = get_post_block_galleries_images( $ID );我希望这个答案能帮助你和其他人。:)
https://stackoverflow.com/questions/55797894
复制相似问题