You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何批量将WordPress文章首图设为特色图并可删除原首图

批量设置WordPress文章特色图并移除首图的Python方案

前置准备

  • 确保WordPress开启XML-RPC功能(后台「设置-撰写」中开启,部分主机可能默认关闭,需手动启用)
  • 安装依赖库:pip install python-wordpress-xmlrpc beautifulsoup4

实现脚本

from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import GetPosts, EditPost
from wordpress_xmlrpc.methods.media import GetMediaLibrary
from bs4 import BeautifulSoup

# 配置WordPress信息
WP_URL = 'https://你的域名/xmlrpc.php'
WP_USER = '管理员用户名'
WP_PASS = '管理员密码'

# 连接WordPress
client = Client(WP_URL, WP_USER, WP_PASS)

def get_attachment_id(image_url):
    """通过图片URL匹配媒体库中的附件ID"""
    media_list = client.call(GetMediaLibrary({'number': 2000}))  # 数值需大于你的媒体文件总数
    for media in media_list:
        if media.link == image_url:
            return media.id
    return None

def process_posts():
    # 获取所有未设置特色图的文章
    target_posts = client.call(GetPosts({
        'post_type': 'post',
        'number': 1000,
        'meta_query': [{'key': '_thumbnail_id', 'compare': 'NOT EXISTS'}]
    }))

    for post in target_posts:
        soup = BeautifulSoup(post.content, 'html.parser')
        first_img = soup.find('img')
        
        if not first_img:
            print(f"文章ID {post.id} 无首图,跳过")
            continue
        
        img_url = first_img['src']
        attach_id = get_attachment_id(img_url)
        
        if not attach_id:
            print(f"文章ID {post.id} 的首图 {img_url} 不在媒体库,跳过")
            continue
        
        # 设置特色图
        post.thumbnail = attach_id
        # 删除文章内的首图
        first_img.decompose()
        post.content = str(soup)
        
        # 更新文章
        try:
            client.call(EditPost(post.id, post))
            print(f"文章ID {post.id} 处理完成")
        except Exception as e:
            print(f"文章ID {post.id} 处理失败:{str(e)}")

if __name__ == '__main__':
    process_posts()

关键注意事项

  • 先备份数据库:批量操作存在风险,务必提前备份WordPress数据库
  • 先测试少量文章:修改GetPosts中的number参数为3-5,验证效果后再全量执行
  • 媒体库数量适配:GetMediaLibrary的number值要大于实际媒体文件总数,避免遗漏图片匹配
  • 权限验证:确保使用的管理员账号拥有编辑文章、管理媒体的权限

内容的提问来源于stack exchange,提问作者Morteza Ahmadi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 22:40:31