Skip to content

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

feat(blocks): Add WordPress Get All Posts block and Publish Post draft toggle (#11003)

Toran Bruce Richardsdb8b43bb3dd8
diff --git a/autogpt_platform/backend/backend/blocks/wordpress/__init__.py b/autogpt_platform/backend/backend/blocks/wordpress/__init__.py
index c7b1e26eea..3eae4a1063 100644
--- a/autogpt_platform/backend/backend/blocks/wordpress/__init__.py
+++ b/autogpt_platform/backend/backend/blocks/wordpress/__init__.py
@@ -1,3 +1,3 @@
-from .blog import WordPressCreatePostBlock
+from .blog import WordPressCreatePostBlock, WordPressGetAllPostsBlock
-__all__ = ["WordPressCreatePostBlock"]
+__all__ = ["WordPressCreatePostBlock", "WordPressGetAllPostsBlock"]
diff --git a/autogpt_platform/backend/backend/blocks/wordpress/_api.py b/autogpt_platform/backend/backend/blocks/wordpress/_api.py
index 78f535947b..d21dc3e05d 100644
--- a/autogpt_platform/backend/backend/blocks/wordpress/_api.py
+++ b/autogpt_platform/backend/backend/blocks/wordpress/_api.py
@@ -161,7 +161,7 @@ async def oauth_exchange_code_for_tokens(
grant_type="authorization_code",
).model_dump(exclude_none=True)
- response = await Requests().post(
+ response = await Requests(raise_for_status=False).post(
f"{WORDPRESS_BASE_URL}oauth2/token",
headers=headers,
data=data,
@@ -205,7 +205,7 @@ async def oauth_refresh_tokens(
grant_type="refresh_token",
).model_dump(exclude_none=True)
- response = await Requests().post(
+ response = await Requests(raise_for_status=False).post(
f"{WORDPRESS_BASE_URL}oauth2/token",
headers=headers,
data=data,
@@ -252,7 +252,7 @@ async def validate_token(
"token": token,
}
- response = await Requests().get(
+ response = await Requests(raise_for_status=False).get(
f"{WORDPRESS_BASE_URL}oauth2/token-info",
params=params,
)
@@ -296,7 +296,7 @@ async def make_api_request(
url = f"{WORDPRESS_BASE_URL.rstrip('/')}{endpoint}"
- request_method = getattr(Requests(), method.lower())
+ request_method = getattr(Requests(raise_for_status=False), method.lower())
response = await request_method(
url,
headers=headers,
@@ -476,6 +476,7 @@ async def create_post(
data["tags"] = ",".join(str(t) for t in data["tags"])
# Make the API request
+ site = normalize_site(site)
endpoint = f"/rest/v1.1/sites/{site}/posts/new"
headers = {
@@ -483,7 +484,7 @@ async def create_post(
"Content-Type": "application/x-www-form-urlencoded",
}
- response = await Requests().post(
+ response = await Requests(raise_for_status=False).post(
f"{WORDPRESS_BASE_URL.rstrip('/')}{endpoint}",
headers=headers,
data=data,
@@ -499,3 +500,132 @@ async def create_post(
)
error_message = error_data.get("message", response.text)
raise ValueError(f"Failed to create post: {response.status} - {error_message}")
+
+
+class Post(BaseModel):
+ """Response model for individual posts in a posts list response.
+
+ This is a simplified version compared to PostResponse, as the list endpoint
+ returns less detailed information than the create/get single post endpoints.
+ """
+
+ ID: int
+ site_ID: int
+ author: PostAuthor
+ date: datetime
+ modified: datetime
+ title: str
+ URL: str
+ short_URL: str
+ content: str | None = None
+ excerpt: str | None = None
+ slug: str
+ guid: str
+ status: str
+ sticky: bool
+ password: str | None = ""
+ parent: Union[Dict[str, Any], bool, None] = None
+ type: str
+ discussion: Dict[str, Union[str, bool, int]] | None = None
+ likes_enabled: bool | None = None
+ sharing_enabled: bool | None = None
+ like_count: int | None = None
+ i_like: bool | None = None
+ is_reblogged: bool | None = None
+ is_following: bool | None = None
+ global_ID: str | None = None
+ featured_image: str | None = None
+ post_thumbnail: Dict[str, Any] | None = None
+ format: str | None = None
+ geo: Union[Dict[str, Any], bool, None] = None
+ menu_order: int | None = None
+ page_template: str | None = None
+ publicize_URLs: List[str] | None = None
+ terms: Dict[str, Dict[str, Any]] | None = None
+ tags: Dict[str, Dict[str, Any]] | None = None
+ categories: Dict[str, Dict[str, Any]] | None = None
+ attachments: Dict[str, Dict[str, Any]] | None = None
+ attachment_count: int | None = None
+ metadata: List[Dict[str, Any]] | None = None
+ meta: Dict[str, Any] | None = None
+ capabilities: Dict[str, bool] | None = None
+ revisions: List[int] | None = None
+ other_URLs: Dict[str, Any] | None = None
+
+
+class PostsResponse(BaseModel):
+ """Response model for WordPress posts list."""
+
+ found: int
+ posts: List[Post]
+ meta: Dict[str, Any]
+
+
+def normalize_site(site: str) -> str:
+ """
+ Normalize a site identifier by stripping protocol and trailing slashes.
+
+ Args:
+ site: Site URL, domain, or ID (e.g., "https://myblog.wordpress.com/", "myblog.wordpress.com", "123456789")
+
+ Returns:
+ Normalized site identifier (domain or ID only)
+ """
+ site = site.strip()
+ if site.startswith("https://"):
+ site = site[8:]
+ elif site.startswith("http://"):
+ site = site[7:]
+ return site.rstrip("/")
+
+
+async def get_posts(
+ credentials: Credentials,
+ site: str,
+ status: PostStatus | None = None,
+ number: int = 100,
+ offset: int = 0,
+) -> PostsResponse:
+ """
+ Get posts from a WordPress site.
+
+ Args:
+ credentials: OAuth credentials
+ site: Site ID or domain (e.g., "myblog.wordpress.com" or "123456789")
+ status: Filter by post status using PostStatus enum, or None for all
+ number: Number of posts to retrieve (max 100)
+ offset: Number of posts to skip (for pagination)
+
+ Returns:
+ PostsResponse with the list of posts
+ """
+ site = normalize_site(site)
+ endpoint = f"/rest/v1.1/sites/{site}/posts"
+
+ headers = {
+ "Authorization": credentials.auth_header(),
+ }
+
+ params: Dict[str, Any] = {
+ "number": max(1, min(number, 100)), # 1–100 posts per request
+ "offset": offset,
+ }
+
+ if status:
+ params["status"] = status.value
+ response = await Requests(raise_for_status=False).get(
+ f"{WORDPRESS_BASE_URL.rstrip('/')}{endpoint}",
+ headers=headers,
+ params=params,
+ )
+
+ if response.ok:
+ return PostsResponse.model_validate(response.json())
+
+ error_data = (
+ response.json()
+ if response.headers.get("content-type", "").startswith("application/json")
+ else {}
+ )
+ error_message = error_data.get("message", response.text)
+ raise ValueError(f"Failed to get posts: {response.status} - {error_message}")
diff --git a/autogpt_platform/backend/backend/blocks/wordpress/blog.py b/autogpt_platform/backend/backend/blocks/wordpress/blog.py
index c0ad5eca54..22b691480b 100644
--- a/autogpt_platform/backend/backend/blocks/wordpress/blog.py
+++ b/autogpt_platform/backend/backend/blocks/wordpress/blog.py
@@ -9,7 +9,15 @@ from backend.sdk import (
SchemaField,
)
-from ._api import CreatePostRequest, PostResponse, PostStatus, create_post
+from ._api import (
+ CreatePostRequest,
+ Post,
+ PostResponse,
+ PostsResponse,
+ PostStatus,
+ create_post,
+ get_posts,
+)
from ._config import wordpress
@@ -49,8 +57,15 @@ class WordPressCreatePostBlock(Block):
media_urls: list[str] = SchemaField(
description="URLs of images to sideload and attach to the post", default=[]
)
+ publish_as_draft: bool = SchemaField(
+ description="If True, publishes the post as a draft. If False, publishes it publicly.",
+ default=False,
+ )
class Output(BlockSchemaOutput):
+ site: str = SchemaField(
+ description="The site ID or domain (pass-through for chaining with other blocks)"
+ )
post_id: int = SchemaField(description="The ID of the created post")
post_url: str = SchemaField(description="The full URL of the created post")
short_url: str = SchemaField(description="The shortened wp.me URL")
@@ -78,7 +93,9 @@ class WordPressCreatePostBlock(Block):
tags=input_data.tags,
featured_image=input_data.featured_image,
media_urls=input_data.media_urls,
- status=PostStatus.PUBLISH,
+ status=(
+ PostStatus.DRAFT if input_data.publish_as_draft else PostStatus.PUBLISH
+ ),
)
post_response: PostResponse = await create_post(
@@ -87,7 +104,69 @@ class WordPressCreatePostBlock(Block):
post_data=post_request,
)
+ yield "site", input_data.site
yield "post_id", post_response.ID
yield "post_url", post_response.URL
yield "short_url", post_response.short_URL
yield "post_data", post_response.model_dump()
+
+
+class WordPressGetAllPostsBlock(Block):
+ """
+ Fetches all posts from a WordPress.com site or Jetpack-enabled site.
+ Supports filtering by status and pagination.
+ """
+
+ class Input(BlockSchemaInput):
+ credentials: CredentialsMetaInput = wordpress.credentials_field()
+ site: str = SchemaField(
+ description="Site ID or domain (e.g., 'myblog.wordpress.com' or '123456789')"
+ )
+ status: PostStatus | None = SchemaField(
+ description="Filter by post status, or None for all",
+ default=None,
+ )
+ number: int = SchemaField(
+ description="Number of posts to retrieve (max 100 per request)", default=20
+ )
+ offset: int = SchemaField(
+ description="Number of posts to skip (for pagination)", default=0
+ )
+
+ class Output(BlockSchemaOutput):
+ site: str = SchemaField(
+ description="The site ID or domain (pass-through for chaining with other blocks)"
+ )
+ found: int = SchemaField(description="Total number of posts found")
+ posts: list[Post] = SchemaField(
+ description="List of post objects with their details"
+ )
+ post: Post = SchemaField(
+ description="Individual post object (yielded for each post)"
+ )
+
+ def __init__(self):
+ super().__init__(
+ id="97728fa7-7f6f-4789-ba0c-f2c114119536",
+ description="Fetch all posts from WordPress.com or Jetpack sites",
+ categories={BlockCategory.SOCIAL},
+ input_schema=self.Input,
+ output_schema=self.Output,
+ )
+
+ async def run(
+ self, input_data: Input, *, credentials: Credentials, **kwargs
+ ) -> BlockOutput:
+ posts_response: PostsResponse = await get_posts(
+ credentials=credentials,
+ site=input_data.site,
+ status=input_data.status,
+ number=input_data.number,
+ offset=input_data.offset,
+ )
+
+ yield "site", input_data.site
+ yield "found", posts_response.found
+ yield "posts", posts_response.posts
+ for post in posts_response.posts:
+ yield "post", post