简体   繁体   中英

WordPress REST API JS Client Returns undefined for Post Attributes

I'm completely new to the WordPress API and I've been following the handbook here . I want to access a post by ID using the API the console log its title and content. I can see the fields when I log the entire object but whenever I try to access the attributes I get "undefined".

My script is rather simple, I've passed the API as a dependancy

wp_enqueue_script('custom', get_stylesheet_directory_uri().'/script.js', array('wp-api'));
wp.api.loadPromise.done( function() {
    var post = new wp.api.models.Post( { id: 1 } );
    post.fetch();
    console.log(post.get("title"))
    console.log(post.title);
    console.log(post.attributes.title)
    
} )

All of my console logs return undefined. Just looking to be pointed in the right direction. Thanks :)

After a bit of researching I realised even though I could see the keys in the console.log this wasn't the state of the object when I was looking for the title. To resolve this I added .done function to the fetch statement

wp.api.loadPromise.done( function() {
    var post = new wp.api.models.Post( { id: 1 } );
    post.fetch().done( function(){
        console.log(post.get("title"))
    });
} )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM