ALL BUSINESS DATA ANALYSIS ENGLISH ARTICLES MICROSOFT EXCEL TIPS MY PROJECTS PYTHON

Streamlined WordPress Media Uploads with REST API Integration

ΕΝ – Use Case: Automating Image Uploads to WordPress and Tracking in Excel


Use Case Overview

This use case describes a Python-based automated system for processing and uploading images to a WordPress website, ensuring that all uploaded images are properly resized, optimized, and documented in an Excel report.

Upload images from a folder


Goal

The primary goal is to streamline the process of managing image uploads to a WordPress site while ensuring:

  • Image consistency through standardized resizing.
  • Automated uploading to WordPress via API.
  • Proper documentation in an Excel file with image thumbnails.

Actors

Primary Actor

  • Content Manager / Website Administrator
    • Responsible for uploading and managing images on WordPress.
    • Uses this automation tool to speed up the process.

Supporting Systems

  • WordPress Media Library (via REST API)
  • Local Storage (Folders for Processed Images & Excel File)

YouTube


Workflow (Main Use Case Scenario)

Step 1: Prepare Images

  • The user places images in a designated folder (folder1).
  • The script will scan and process JPEG, PNG, WEBP, GIF formats.

Step 2: Load Configuration & Credentials

  • The script loads WordPress credentials (URL, username, API password) from a .env file.
  • If credentials are missing, the script exits with an error.

Step 3: Process Images

  • Each image in the folder undergoes:
    1. Resizing → Adjusted to 800x800 pixels for web optimization.
    2. Thumbnail Creation → A 64x64 pixel version is generated.

Step 4: Upload Images to WordPress

  • The script authenticates with WordPress API and uploads the images.
  • Metadata such as alt text (formatted from file name) is included.
  • If an upload fails, the error message is displayed.

Step 5: Document Uploaded Images

  • The script saves the following details in an Excel file (upload_details.xlsx):
    • Local file path
    • Uploaded WordPress image URL
    • Thumbnail preview embedded in Excel

Step 6: Organize Files

  • Resized images are stored in a resized/ folder.
  • Thumbnails are stored in a thumbnails/ folder.
  • The Excel file is saved with upload records.

Alternative Scenarios & Error Handling

Scenario System Behavior
.env file is missing The script exits with an error message.
Invalid API credentials Uploads will fail, and the script logs an error.
Unsupported file formats These files are skipped.
Image fails to process (corrupt file, etc.) The script logs the error and continues with the next file.
WordPress API returns an error (e.g., server down) The script logs the error and retries later.

Benefits of Using This System

Saves Time – Eliminates manual uploading of images.
Ensures Consistency – Resizes images uniformly.
Improves Organization – Keeps track of uploaded images in Excel.
Reduces Errors – Handles failures and logs issues.
Enhances WordPress SEO – Automatically generates alt text from file names.


Future Enhancements

Bulk Post Creation – Extend functionality to create WordPress posts with uploaded images.
Image Compression – Reduce file size further before uploading.
Drag & Drop Interface – A GUI version for non-technical users.


Conclusion

This automated system simplifies image management for WordPress, making it an ideal solution for bloggers, content managers, and businesses handling large media uploads.

GR – Use Case: Αυτοματοποιημένη Μεταφόρτωση Εικόνων στο WordPress και Καταγραφή σε Excel


Σκοπός

Η αυτοματοποίηση της διαδικασίας μεταφόρτωσης εικόνων σε έναν ιστότοπο WordPress, διασφαλίζοντας ότι όλες οι εικόνες:

  • Προσαρμόζονται σε σταθερό μέγεθος για βελτιστοποίηση.
  • Ανεβαίνουν αυτόματα μέσω του WordPress REST API.
  • Καταγράφονται σε αρχείο Excel με ενσωματωμένα thumbnails.

upload images from a folder


Συμμετέχοντες (Actors)

  • Διαχειριστής Ιστότοπου – Χρησιμοποιεί το script για να ανεβάζει εικόνες.
  • WordPress Media Library – Το σύστημα αποθήκευσης εικόνων μέσω API.
  • Τοπικό Σύστημα (Υπολογιστής) – Οργανώνει τις εικόνες και αποθηκεύει το Excel.

Ροή Εργασιών (Workflow)

1️⃣ Ο χρήστης τοποθετεί τις εικόνες σε έναν φάκελο.
2️⃣ Το script διαβάζει τα αρχεία και τις προσαρμόζει σε 800×800 pixels.
3️⃣ Δημιουργείται μικρογραφία (thumbnail) 64×64 pixels.
4️⃣ Οι εικόνες ανεβαίνουν αυτόματα στο WordPress.
5️⃣ Το script αποθηκεύει ένα αρχείο Excel με:

  • Τοπική διαδρομή εικόνας.
  • URL της εικόνας στο WordPress.
  • Μικρογραφία ενσωματωμένη στο Excel.

Εναλλακτικά Σενάρια & Διαχείριση Σφαλμάτων

Σενάριο Συμπεριφορά Συστήματος
Απουσία αρχείου .env Το script τερματίζεται με μήνυμα σφάλματος.
Λάθος διαπιστευτήρια API Οι μεταφορτώσεις αποτυγχάνουν.
Μη υποστηριζόμενος τύπος αρχείου Το αρχείο παραλείπεται.
Σφάλμα επεξεργασίας εικόνας Το script παραλείπει την εικόνα και συνεχίζει.
Αποτυχία μεταφόρτωσης λόγω προβλήματος WordPress Το script καταγράφει το σφάλμα για μελλοντική επανεκτέλεση.

Οφέλη

Αυτοματοποιεί τη διαδικασία μεταφόρτωσης εικόνων.
Διασφαλίζει ομοιομορφία μεγέθους εικόνων.
Παρακολουθεί όλες τις εικόνες σε οργανωμένο Excel.
Μειώνει τα σφάλματα και τον χρόνο εργασίας.


Συμπέρασμα

Αυτό το script απλοποιεί και επιταχύνει τη διαδικασία διαχείρισης εικόνων στο WordPress, καθιστώντας το ιδανικό για bloggers, διαχειριστές ιστοσελίδων και εταιρείες με μεγάλο όγκο πολυμέσων.

Python Script Solution: Automating Image Uploads to WordPress and Tracking in Excel.

streamlined wordpress media uploads

This Python script [upload_images_4.py] automates the process of resizing images, uploading them to a WordPress website, and tracking upload details in an Excel file. Below is a breakdown of how the script works and its key functionalities.

streamlined wordpress media uploads


Key Features of the Script

  1. Loads WordPress API Credentials
    • Retrieves WP_URL, WP_USER, and WP_APP_PASSWORD from a .env file.
    • Ensures all credentials are correctly loaded before proceeding.
  2. Resizes Images for Web Optimization
    • Images are resized to 800x800 pixels (standard size).
    • Creates a 64x64 pixel thumbnail for reference in Excel.
  3. Uploads Images to WordPress via REST API
    • Uses Basic Authentication to interact with the WordPress API.
    • Sends images to /wp-json/wp/v2/media for media library storage.
    • Assigns an appropriate alt text based on the file name.
  4. Stores Upload Details in an Excel File
    • Saves details such as:
      • Local file path
      • Uploaded image URL
      • Thumbnail preview
    • Formats Excel with bold headers, column width adjustments, and embedded thumbnail previews.
  5. Organizes Processed Images into Folders
    • resized/ → Stores resized images.
    • thumbnails/ → Stores small preview thumbnails.

upload images from a folder

    • upload_details.xlsx → Saves upload data for reference.

upload images from a folderupload images from a folder


Step-by-Step Code Explanation

1️⃣ Load Environment Variables

dotenv_path = r"c:\pythonprograms\wordpress_media_upload\dot_env.env"
if not os.path.exists(dotenv_path):
    print(f".env file not found at: {dotenv_path}")
    exit(1)

load_dotenv(dotenv_path=dotenv_path)

WP_URL = os.getenv('WP_URL')
WP_USER = os.getenv('WP_USER')
WP_APP_PASSWORD = os.getenv('WP_APP_PASSWORD')

if not WP_URL or not WP_USER or not WP_APP_PASSWORD:
    print("Failed to load environment variables. Check your .env file.")
    exit(1)
  • This checks for the .env file containing WordPress API credentials.
  • If credentials are missing, the script exits with an error message.

2️⃣ Define Image Processing Functions

Resize Image

def resize_image(input_path, output_path, size):
    with Image.open(input_path) as img:
        img = img.resize(size, Image.Resampling.LANCZOS)
        img.save(output_path, quality=95)
  • Uses the PIL (Pillow) library to resize images.
  • Resizes using LANCZOS resampling for high quality.
  • Saves with quality=95 for good compression without major loss.

Create Thumbnail

def create_thumbnail(image_path, thumbnail_path):
    with Image.open(image_path) as img:
        img = img.resize(THUMBNAIL_SIZE, Image.Resampling.LANCZOS)
        img.save(thumbnail_path, quality=95)
  • Generates a small 64x64 pixel thumbnail.
  • Saves it for use in the Excel file.

3️⃣ Upload Image to WordPress

def upload_image_to_wordpress(file_path):
    media_url = f"{WP_URL}/wp-json/wp/v2/media"
    headers = create_auth_header(WP_USER, WP_APP_PASSWORD)
    file_name = os.path.basename(file_path)
    alt_text = os.path.splitext(file_name)[0].replace("-", " ").replace("_", " ").capitalize()

    with open(file_path, 'rb') as img:
        mime_type, _ = mimetypes.guess_type(file_path)
        files = {'file': (file_name, img, mime_type or 'application/octet-stream')}
        data = {'alt_text': alt_text}
        response = requests.post(media_url, headers=headers, files=files, data=data)

    if response.status_code == 201:
        uploaded_url = response.json().get('guid', {}).get('rendered', 'URL not found')
        print(f"Uploaded {file_path} successfully: {uploaded_url}")
        return uploaded_url
    else:
        print(f"Failed to upload {file_path}. Status: {response.status_code}, Response: {response.text}")
        return None
  • Uses requests to upload images via the WordPress REST API.
  • Assigns a friendly alt text based on the file name.
  • Handles different image MIME types automatically.
  • Prints success or failure messages.

4️⃣ Process Images & Upload

def process_and_upload_images(folder_path, size):
    resized_folder = os.path.join(folder_path, "resized")
    thumbnails_folder = os.path.join(folder_path, "thumbnails")
    os.makedirs(resized_folder, exist_ok=True)
    os.makedirs(thumbnails_folder, exist_ok=True)

    upload_details = []

    for file_name in os.listdir(folder_path):
        input_path = os.path.join(folder_path, file_name)
        if os.path.isfile(input_path) and file_name.lower().endswith(('webp', 'jpg', 'jpeg', 'png', 'gif')):
            output_path = os.path.join(resized_folder, file_name)
            thumbnail_path = os.path.join(thumbnails_folder, file_name)

            try:
                resize_image(input_path, output_path, size)
                create_thumbnail(output_path, thumbnail_path)
                print(f"Processed {file_name}.")
            except Exception as e:
                print(f"Failed to process {file_name}: {e}")
                continue

            try:
                uploaded_url = upload_image_to_wordpress(output_path)
                if uploaded_url:
                    upload_details.append({
                        "Local File Path": output_path,
                        "Uploaded File URL": uploaded_url,
                        "Thumbnail Path": thumbnail_path
                    })
            except Exception as e:
                print(f"Failed to upload {file_name}: {e}")

    if upload_details:
        save_details_to_excel(upload_details, folder_path)
  • Loops through files in the folder, processes images, and uploads them.
  • Stores upload details (local path, uploaded URL, thumbnail path).

5️⃣ Save Details in Excel

def save_details_to_excel(upload_details, folder_path):
    excel_path = os.path.join(folder_path, "upload_details.xlsx")
    workbook = Workbook()
    sheet = workbook.active
    sheet.title = "Uploaded Files"

    # Write headers
    headers = ["Local File Path", "Uploaded File URL", "Thumbnail"]
    sheet.append(headers)

    # Style headers
    header_font = Font(bold=True)
    for col, header in enumerate(headers, start=1):
        cell = sheet.cell(row=1, column=col)
        cell.font = header_font
        cell.alignment = Alignment(horizontal="center", vertical="center")

    # Write rows
    for detail in upload_details:
        sheet.append([detail["Local File Path"], detail["Uploaded File URL"]])

    # Add thumbnails
    for row_index, detail in enumerate(upload_details, start=2):
        thumbnail_path = detail.get("Thumbnail Path", "")
        if os.path.exists(thumbnail_path):
            img = ExcelImage(thumbnail_path)
            img.width, img.height = 64, 64
            sheet.add_image(img, f"C{row_index}")
            sheet.row_dimensions[row_index].height = 48

    workbook.save(excel_path)
    print(f"Upload details saved to {excel_path}")
  • Uses OpenPyXL to save upload details to an Excel spreadsheet.
  • Adds a column for thumbnails with embedded images.

How to Use the Script

  1. Ensure WordPress API credentials are stored in dot_env.env.
  2. Place images in the designated folder (folder1).
  3. Run the script:
    python upload_images_4.py
    
  4. The script will:
    • Resize images
    • Upload them to WordPress
    • Save details (including thumbnails) in upload_details.xlsx.

Upload details


Final Thoughts

This script automates image processing and uploads for WordPress, making bulk media uploads seamless and efficient. Perfect for bloggers, content managers, or businesses managing large image libraries!

Views: 12

Comments are closed.

Pin It