【问题标题】:Get post thumbnail with Wordpress REST API使用 Wordpress REST API 获取帖子缩略图
【发布时间】: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' );

【问题讨论】:

    标签: wordpress api rest post


    【解决方案1】:

    您正在寻找has_post_thumbnail、the_post_thumbnail 和the_post_thumbnail_url。


    示例

    <?php
    /**
    * The Loop
    * @link https://developer.wordpress.org/themes/basics/the-loop/
    */
    if ( have_posts() ):
        while ( have_posts() ): the_post();
    
          /**
          * has_post_thumbnail()
          * @link https://developer.wordpress.org/reference/functions/has_post_thumbnail/
          */
          if ( has_post_thumbnail() ):
            the_post_thumbnail();
    
            /**
            * get_the_post_thumbnail_url()
            * @link https://developer.wordpress.org/reference/functions/get_the_post_thumbnail_url/
            */
            the_post_thumbnail_url();
          endif;
        endwhile;
    endif; ?>
    

    了解详情

    【讨论】:

    • 这个解决方案不起作用,我从另一个 Wordpress 网站获得了带有 json 的帖子,我需要代码来显示帖子图片、标题和链接工作完美
    猜你喜欢
    • 1970-01-01
    • 2018-04-05
    • 2014-03-12
    • 2011-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 2014-11-13
    相关资源
    最近更新 更多