Hướng dẫn tích hợp mã Python vào website WordPress sử dụng Theme Flatsome

Để tích hợp mã Python vào website WordPress sử dụng theme Flatsome, bạn có thể làm theo các bước sau:

Cách làm:

  1. Tạo API bằng Python (Flask/FastAPI) để xử lý ảnh.

  2. Tạo giao diện tải ảnh lên trong WordPress bằng shortcode.

  3. Sử dụng AJAX để gửi ảnh đến API và nhận kết quả.

Tạo API xử lý ảnh bằng Flask

Bạn cần có một server chạy Python để xử lý ảnh. Dưới đây là cách tạo API với Flask:

Bước 1: Cài đặt Flask & Pillow

pip install flask pillow

Bước 2: Viết API xử lý ảnh

Lưu file dưới tên app.py:

from flask import Flask, request, jsonify, send_file
from PIL import Image
import os
app = Flask(__name__)
UPLOAD_FOLDER = “uploads”
PROCESSED_FOLDER = “processed”
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(PROCESSED_FOLDER, exist_ok=True)
def split_image(image_path):
    base_name = os.path.splitext(os.path.basename(image_path))[0]
    img = Image.open(image_path)
    width, height = img.size
    if width != 2358 or height != 1800:
        return {“error”: “Kích thước ảnh phải là 2358x1800px”}
    regions = [
        (0, 0, 1179, 900),
        (1179, 0, 2358, 900),
        (0, 900, 786, 1800),
        (786, 900, 1572, 1800),
        (1572, 900, 2358, 1800)
    ]
    output_files = []
    for i, region in enumerate(regions):
        cropped_img = img.crop(region)
        output_path = os.path.join(PROCESSED_FOLDER, f”{base_name}_{i+1}.png”)
        cropped_img.save(output_path)
        output_files.append(output_path)
    return output_files
@app.route(‘/upload’, methods=[‘POST’])
def upload_image():
    if ‘image’ not in request.files:
        return jsonify({“error”: “Không tìm thấy ảnh”}), 400
    file = request.files[‘image’]
    if file.filename == ”:
        return jsonify({“error”: “Tên file không hợp lệ”}), 400
    file_path = os.path.join(UPLOAD_FOLDER, file.filename)
    file.save(file_path)
    output_files = split_image(file_path)
    if isinstance(output_files, dict):
        return jsonify(output_files), 400
    return jsonify({“success”: True, “images”: output_files})
@app.route(‘/download/<filename>’, methods=[‘GET’])
def download_file(filename):
    return send_file(os.path.join(PROCESSED_FOLDER, filename), as_attachment=True)
if __name__ == ‘__main__’:
    app.run(host=”0.0.0.0″, port=5000, debug=True)
Chạy API: python app.py
Giờ API của bạn chạy ở http://your-server-ip:5000/upload

2️⃣ Thêm giao diện tải ảnh lên WordPress

Bạn sẽ tạo một shortcode trong WordPress để hiển thị form tải ảnh lên.

Bước 1: Thêm đoạn code sau vào functions.php của theme Flatsome:

Code:

function image_splitter_form() {
    ob_start();
    ?>
    <form id=”imageUploadForm” enctype=”multipart/form-data”>
        <input type=”file” id=”imageInput” name=”image” accept=”image/png, image/jpeg” required>
        <button type=”button” id=”uploadBtn”>Tải lên & Chia ảnh</button>
    </form>
    <div id=”result”></div>
    <script>
        document.getElementById(“uploadBtn”).addEventListener(“click”, function() {
            var formData = new FormData();
            var imageFile = document.getElementById(“imageInput”).files[0];
            if (!imageFile) {
                alert(“Vui lòng chọn ảnh!”);
                return;
            }
            formData.append(“image”, imageFile);
            fetch(“http://your-server-ip:5000/upload”, {
                method: “POST”,
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    let resultDiv = document.getElementById(“result”);
                    resultDiv.innerHTML = “<h3>Ảnh đã chia:</h3>”;
                    data.images.forEach(img => {
                        let imgName = img.split(‘/’).pop();
                        resultDiv.innerHTML += `<a href=”http://your-server-ip:5000/download/${imgName}” target=”_blank”>Tải ${imgName}</a><br>`;
                    });
                } else {
                    alert(data.error);
                }
            })
            .catch(error => console.error(“Lỗi:”, error));
        });
    </script>
    <?php
    return ob_get_clean();
}
add_shortcode(‘image_splitter’, ‘image_splitter_form’);

Bước 2: Thêm shortcode vào trang bất kỳ

Truy cập Trang/Trang chủ > Chỉnh sửa và chèn đoạn này vào bài viết hoặc trang: [image_splitter]

3️⃣ Hoàn thành

  • Khi truy cập trang có shortcode [image_splitter], người dùng có thể tải ảnh lên.

  • Ảnh sẽ được gửi đến API xử lý và trả về các link tải ảnh đã chia nhỏ.

  • Người dùng có thể tải xuống từng ảnh bằng cách nhấn vào link.

Lưu ý

  1. Bạn cần một server chạy Python (VPS hoặc hosting có hỗ trợ Flask).

  2. Nếu host WordPress và API cùng server, dùng localhost thay vì your-server-ip.

  3. Nếu gặp lỗi CORS, hãy cài đặt thư viện: pip install flask-cors

Và thêm vào app.py:

from flask_cors import CORS
CORS(app)