讓 AI 把手動處理變自動

目前我的網站是使用 WordPress 架設,並套用了一個佈景主題。不過裡面有些風格和設計我不太喜歡,想要自己調整。

一開始,我是透過手動修改程式碼的方式來調整,步驟如下:

Bash

cd /var/www/stackoverflow/wp-content/themes/gutenshop

1. 移除關於作者的區塊

編輯 single.php,刪除第 39 到 52 行的 PHP 程式碼:

PHP

// About the author start
echo '<div class="about-the-author">';
echo '<div class="grid-x grid-padding-x">';
echo '<div class="large-2 medium-3 small-12 cell">';
echo get_avatar( get_the_author_meta( 'ID' ), 100 );
echo '</div>';
echo '<div class="large-10 medium-9 small-12 cell">';
echo '<h3>';
echo esc_html('About the author','gutenshop');
echo '</h3>';
echo nl2br(get_the_author_meta('description'));
echo '</div>';
echo '</div>';
echo '</div>';
// About the author end

2. 修改日期顯示格式

將原本的 F j, Y 格式,全部改為 Y-m-d 格式。

修改 single.phptemplate-parts/content-excerpt.php

  • 原本的程式碼:PHPecho esc_html(get_the_date('F j, Y'));
  • 修改後的程式碼:PHPecho esc_html(get_the_date('Y-m-d'));

3. 隱藏文章發表者資訊

編輯 template-parts/content-search.phptemplate-parts/content.php,將顯示發表者的函式註解掉:

  • 原本的程式碼:PHPguten_shop_posted_by();
  • 修改後的程式碼:PHP//guten_shop_posted_by();

4. 移除日期前方的文字

編輯 inc/template-tags.php,把原本顯示的 Posted on 字樣拿掉:

  • 原本的程式碼:PHPesc_html_x( 'Posted on %s', 'post date', 'gutenshop' ),
  • 修改後的程式碼:PHPesc_html_x( '%s', 'post date', 'gutenshop' ),

雖然手動修改可以達到效果,但每次佈景主題更新後,這些修改就會被覆蓋,又得重新來過一遍,非常麻煩。

於是,我把上面這些手動修改的步驟和需求直接貼給 AI ,並加上一句:

幫我產生 patch script

沒想到 AI 馬上就寫好了一個 Python 自動化腳本,把上面所有檔案的修改邏輯全部寫進去。

以後佈景主題更新時,我只要在終端機執行這個腳本,一秒就能自動完成所有的改版與修正,真的非常方便!

script:

import os
import re

def patch_theme(theme_path):
    """
    Applies patches to the Gutenshop theme files to customize the layout and formatting.
    Based on requirements from: https://max-everyday.com/2026/06/ai-generate-patch-script/
    """
    print(f"Starting patch process in: {theme_path}")

    # 1. Remove "About the Author" in single.php and update date format
    single_php = os.path.join(theme_path, 'single.php')
    if os.path.exists(single_php):
        with open(single_php, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # Remove "About the author" block if it exists
        author_pattern = r'// About the author start.*?// About the author end'
        new_content = re.sub(author_pattern, '', content, flags=re.DOTALL)
        
        # Standardize date format to Y-m-d
        # Matches both get_the_date() and get_the_date('F j, Y')
        new_content = new_content.replace("get_the_date('F j, Y')", "get_the_date('Y-m-d')")
        new_content = new_content.replace("get_the_date()", "get_the_date('Y-m-d')")
        
        if new_content != content:
            with open(single_php, 'w', encoding='utf-8') as f:
                f.write(new_content)
            print(f"Patched: {single_php}")
        else:
            print(f"No changes needed for: {single_php}")

    # 2. Modify Date Format in template-parts/content-excerpt.php
    excerpt_php = os.path.join(theme_path, 'template-parts/content-excerpt.php')
    if os.path.exists(excerpt_php):
        with open(excerpt_php, 'r', encoding='utf-8') as f:
            content = f.read()
        
        new_content = content.replace("get_the_date('F j, Y')", "get_the_date('Y-m-d')")
        new_content = new_content.replace("get_the_date()", "get_the_date('Y-m-d')")
        
        if new_content != content:
            with open(excerpt_php, 'w', encoding='utf-8') as f:
                f.write(new_content)
            print(f"Patched: {excerpt_php}")
        else:
            print(f"No changes needed for: {excerpt_php}")

    # 3. Hide Author Info in content-search.php and content.php
    author_files = [
        'template-parts/content-search.php',
        'template-parts/content.php'
    ]
    for rel_path in author_files:
        full_path = os.path.join(theme_path, rel_path)
        if os.path.exists(full_path):
            with open(full_path, 'r', encoding='utf-8') as f:
                content = f.read()
            
            # Comment out the author call if not already commented
            # This handles both <?php guten_shop_posted_by(); ?> and just the function call
            new_content = re.sub(r'(?<!//)guten_shop_posted_by\(\);', '//guten_shop_posted_by();', content)
            
            if new_content != content:
                with open(full_path, 'w', encoding='utf-8') as f:
                    f.write(new_content)
                print(f"Patched: {full_path}")
            else:
                print(f"No changes needed for: {full_path}")

    # 4. Remove "Posted on" text in inc/template-tags.php
    tags_php = os.path.join(theme_path, 'inc/template-tags.php')
    if os.path.exists(tags_php):
        with open(tags_php, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # Change 'Posted on %s' to just '%s'
        old_str = "esc_html_x( 'Posted on %s', 'post date', 'gutenshop' )"
        new_str = "esc_html_x( '%s', 'post date', 'gutenshop' )"
        new_content = content.replace(old_str, new_str)
        
        if new_content != content:
            with open(tags_php, 'w', encoding='utf-8') as f:
                f.write(new_content)
            print(f"Patched: {tags_php}")
        else:
            print(f"No changes needed for: {tags_php}")

if __name__ == "__main__":
    # Use the current directory as the theme path
    target_theme_dir = os.getcwd()
    
    if os.path.isdir(target_theme_dir):
        patch_theme(target_theme_dir)
        print("Patching process completed.")
    else:
        print(f"Error: Directory not found: {target_theme_dir}")

patch fontsize if <=20, fontsize+3, if >20, fontsize +5

import re

def update_font_size(match):
    value = float(match.group(1))
    unit = match.group(2)
    if value <= 20:
        new_value = value + 3
    else:
        new_value = value + 5
    # Keep integer if no fractional part
    if new_value == int(new_value):
        return f"font-size: {int(new_value)}{unit}"
    return f"font-size: {new_value}{unit}"

input_file = r"style.css"
output_file = r"style_updated.css"

with open(input_file, "r", encoding="utf-8") as f:
    content = f.read()

# Match font-size: <number><unit> (px, em, rem, pt, %)
pattern = re.compile(r'font-size:\s*(\d+(?:\.\d+)?)(px|em|rem|pt|%)', re.IGNORECASE)
updated_content = pattern.sub(update_font_size, content)

with open(output_file, "w", encoding="utf-8") as f:
    f.write(updated_content)

# Report changes
matches = pattern.findall(content)
print(f"Updated {len(matches)} font-size value(s).")
print(f"Output written to: {output_file}")

# Auto replace: backup style.css -> style_back.css, set ownership, rename output
import os, shutil, subprocess

backup_file = r"style_back.css"

# chown www-data:www-data on the updated file (Linux only)
try:
    subprocess.run(["chown", "www-data:www-data", output_file], check=True)
    print(f"chown www-data:www-data {output_file}")
except (FileNotFoundError, subprocess.CalledProcessError) as e:
    print(f"chown skipped: {e}")

# Backup original style.css -> style_back.css
if os.path.exists(input_file):
    shutil.move(input_file, backup_file)
    print(f"Backed up: {input_file} -> {backup_file}")

# Rename output to style.css
shutil.move(output_file, input_file)
print(f"Replaced: {output_file} -> {input_file}")

Facebook網友回應

您可能也會感興趣的文章...

大侦探皮卡丘

生活小事

[BT][大侦探皮卡丘][HD-MP4/2.13GB][英语中字][1080P高清版] 畫質不錯 @_@;怎麼會這麼快就下載的到? 又名: 精灵宝可梦:大侦探皮卡丘 / […]

Read More

LINE 免費貼圖 2025-01-07

生活小事

這周有很多新年貼圖, 超讚的, 過年從 2025/01/27星期一開始放假,祝新年快樂,蛇年發大財。 * 加完好友下載完貼圖,請記得「封鎖」官方好友,以免收到廣告。 🇹🇼 […]

Read More

知名女星溫翠蘋遭丈夫毆打

生活小事

2024-01-18日(星期四) 晚上10點半在台北市大安區東豐街一間餐酒館用餐,散場時夫妻產生肢體衝突,丈夫狠踹溫翠蘋多下,溫翠蘋當場放聲尖叫,引來附近店家注意,坐在坐 […]

Read More

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *