【发布时间】:2021-04-06 06:28:45
【问题描述】:
我使用此代码通过 Wordpress REST API 获取帖子,此代码非常有效并且可以很好地发布帖子,但我不知道如何获得帖子缩略图。我在 wp_remote_get 函数中将 ?_embed 添加到 URL 的末尾,并且缩略图地址在输出中,但我不知道如何在 php 中获取和显示图像 url。
<?php
function get_posts_via_rest() {
// Initialize variable.
$allposts = '';
// Enter the name of your blog here followed by /wp-json/wp/v2/posts and add filters like this one that limits the result to 2 posts.
$response = wp_remote_get( 'https://video.amniat98.com/wp-json/wp/v2/posts?_embed' );
// Exit if error.
if ( is_wp_error( $response ) ) {
return;
}
// Get the body.
$posts = json_decode( wp_remote_retrieve_body( $response ) );
// Exit if nothing is returned.
if ( empty( $posts ) ) {
return;
}
// If there are posts.
if ( ! empty( $posts ) ) {
// For each post.
foreach ( $posts as $post ) {
// Use print_r($post); to get the details of the post and all available fields
//print_r($post);
// Show a linked title and post date.
$allposts .= '<a href="' . esc_url( $post->link ) . '" target=\"_blank\">' . esc_html( $post->title->rendered ) . '</a>';
}
return $allposts;
}
}
// Register as a shortcode to be used on the site.
add_shortcode( 'rest_posts', 'get_posts_via_rest' );
【问题讨论】: