Action Code to Publish to WordPress

So I am trying to write some Python code to use the Wordpress API to publish a Post. I don’t get the full error message so I am not sure what’s wrong. I am not sure if this is a bug or if its a problem in my code. Here is the Error message. “Image build for im-ss3uyX8TNhRu5BPgewNSsM failed with the exception: task exited with failure, status = exit status: 1”

Here is the code:

"

import os
import requests
import json

def publish_to_wordpress(wordpress_api_key: str, wordpressurl: str, featuredimageurl: str, post_content: str):
“”"
Publishes a post with featured image to wordpress.

Args:
    wordpress_api_key (string): The WordPress API Key
    wordpressurl (string): The Website URL
    featuredimageurl (string): The URL to the featured Image
    post_content (string): The HTML Content for the Website
"""

  try:
    # First, download and upload the featured image
    image_response = requests.get(featuredimageurl)
    if image_response.status_code != 200:
        return f"Failed to download featured image. Status code: {image_response.status_code}"

    # Upload the image to WordPress
    files = {
        'file': ('featured-image.jpg', image_response.content, 'image/jpeg')
    }
    headers = {
        'IWC-API-KEY': wordpress_api_key
    }
    
    upload_response = requests.post(
        f"{wordpressurl.rstrip('/')}/wp-json/wp/v2/media",
        headers=headers,
        files=files
    )
    
    if upload_response.status_code != 201:
        return f"Failed to upload featured image. Status code: {upload_response.status_code}, Response: {upload_response.text}"
        
    # Parse the upload response
    response_data = parse_wordpress_response(upload_response)
    if not response_data:
        return "Failed to get response data from media upload"
        
    # Get media ID from response
    media_id = response_data.get('ID') or response_data.get('id')
    if not media_id:
        return f"Failed to get media ID from upload response"
    
    # Create the post with the featured image
    post_data = {
        "title": "New WordPress Post",
        "content": post_content,
        "status": "draft",
        "featured_media": media_id
    }
    
    post_response = requests.post(
        f"{wordpressurl.rstrip('/')}/wp-json/wp/v2/posts",
        headers=headers,
        json=post_data
    )
    
    if post_response.status_code in [200, 201]:
        try:
            result = parse_wordpress_response(post_response)
            if not result:
                return "Failed to parse post creation response"
                
            post_id = result.get('id') or result.get('ID')
            post_url = result.get('link') or result.get('guid')
            if post_id and post_url:
                return f"Successfully created post. Post ID: {post_id}, URL: {post_url}"
            else:
                return "Post created but failed to get post details"
        except Exception as e:
            return f"Post created but failed to parse response: {str(e)}"
    else:
        return f"Failed to create post. Status code: {post_response.status_code}, Response: {post_response.text}"
        
except Exception as e:
    return f"An error occurred: {str(e)}"

def parse_wordpress_response(response):
“”“Helper function to parse WordPress API responses”“”
if not response.text:
return None

# If response is already a dict, return it
if isinstance(response, dict):
    return response
    
# Handle the response text
text = response.text
if text.startswith('"') and text.endswith('"'):
    # Remove surrounding quotes and unescape
    text = text[1:-1].encode().decode('unicode_escape')

try:
    return json.loads(text)
except Exception as e:
    print(f"Debug - Response text: {text[:100]}...")  # First 100 chars
    raise Exception(f"Failed to parse response: {str(e)}")

"

I tested the function call in my environment and it works. if the requests package and the json package are installed. “result = publish_to_wordpress(
wordpress_api_key=“your_api_key”,
wordpressurl=“https://your-site.com”,
featuredimageurl=“https://path-to-image.jpg”,
post_content=”

Your HTML Content

"
)
print(result)"

Did you add the json package in the lefthand panel? That could be the issue.

yeah. What I did I moved the main code out to Cloudflare and just kept an API call in there and got it to work.

1 Like