Search code examples
pythonwordpressxml-rpc

How can i grab the ID of all posts?


Recently got into the XML-RPC Library in python and i need to grab the ID of all posts in my wordpress website. I tried using the EditPost() command but it seems that the ID of the posts are needed.

In the following code i am trying to change all posts to draft

from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods import posts
from wordpress_xmlrpc import WordPressPost
from wordpress_xmlrpc.methods.posts import GetPosts, NewPost
from wordpress_xmlrpc.methods.users import GetUserInfo
from wordpress_xmlrpc.methods.posts import EditPost

wp = Client('website-link', 'x', 'x')

post = WordPressPost()
#Posts returns the name of the posts not IDs
posts = wp.call(posts.GetPosts())
print(posts)


for post in posts:
    post.post_status = 'draft'
    wp.call(EditPost(post,post))
print('done')

Solution

  • According to the documentation, the WordPressPost object has an id attribute. Printing the post won't show it, which is maybe why you thought it wasn't there? This code worked for me:

    from wordpress_xmlrpc import Client
    from wordpress_xmlrpc.methods.posts import GetPosts
    wp = Client("https://wordpress.example.com/xmlrpc.php", "admin", "password")
    allposts = wp.call(GetPosts())
    for thepost in allposts:
        print thepost.id
    

    So your code should work by changing your loop as follows:

    for post in posts:
        post.post_status = 'draft'
        wp.call(EditPost(post.id, post))