更改WordPress主题后,REST API不起作用

时间:2019-07-15 作者:Roga Men

RESTAPI与默认主题2616完美配合,但当我更改主题时,网站上的帖子不会出现。有人有确切的问题吗?

<script type="text/javascript">
$(document).ready(function () {
    $.ajax({
        type: \'GET\',
        url: \'https://mywebsite.com/blog/wp-json/wp/v2/posts?_embed&per_page=3\',            

        success: function (data) {
            var posts_html = \'\';
            $.each(data, function (index, post) {
              //posts_html += \'<a href="\' + post.link + \'"><h2>\' + post.title.rendered + \'</h2></a>\';
              //posts_html += \'<p>\' + post.excerpt.rendered + \'</p>\';
              posts_html += \'<div class="blogpost">\';
              posts_html += \'<div class="post-item">\'
              posts_html += \'<div class="post-item-image">\';
              posts_html += \'<a href="\' + post.source_url + \'"></a>\';
              posts_html += \'<img src="\' + post.images.large + \'" alt="\'+ post.title.rendered + \'"</div>\';
              posts_html += \'<div class="post-item-header">\';
              posts_html += \'<span class="date">\' + moment(post.date).format("Do MMM YY") + \'</span>\';
              posts_html += \'<span class="user">\';
              posts_html += \'<a href="\' + post.link +\'">\';
              posts_html += \'<img src="https://mywebsite.com/img/p2plogo.png" alt="P2Pbench logo" >P2Pbench</a></span></div>\';
              posts_html += \'<div class="post-item-body">\';
              posts_html += \'<a href="\' + post.link + \'" style="text-decoration: underline;"> \'+ post.title.rendered + \'</a>\';
              posts_html += \'<div class="post-short-text"> \' + post.excerpt.rendered + \'</div></div></div></div></div>\';
            });
            $(\'#posts\').html(posts_html);
        },
        error: function (request, status, error) {
            alert(error);
        }
    });
});

HTML:

     <div class="blogs-post-list">
    <div id="posts">Loading posts...
   </div>
    </div>

1 个回复
SO网友:Roga Men

我通过将此代码(在底部)添加到您的博客主题我的路径中来解决它:wp content/THEMES/MYWPTHEME/function。php

    function ws_register_images_field() {
    register_rest_field( 
        \'post\',
        \'images\',
        array(
            \'get_callback\'    => \'ws_get_images_urls\',
            \'update_callback\' => null,
            \'schema\'          => null,
        )
    );
}

add_action( \'rest_api_init\', \'ws_register_images_field\' );

function ws_get_images_urls( $object, $field_name, $request ) {
    $medium = wp_get_attachment_image_src( get_post_thumbnail_id( $object->id ), \'medium\' );
    $medium_url = $medium[\'0\'];

    $large = wp_get_attachment_image_src( get_post_thumbnail_id( $object->id ), \'large\' );
    $large_url = $large[\'0\'];

    return array(
        \'medium\' => $medium_url,
        \'large\'  => $large_url,
    );
}