使用PHP代码批量更新文章内容

前言

之前文章提到网站去除登录/评论的短代码,那如何批量去除呢?其实有不少办法,这篇文章教大家如何用php实现。

教程

在此之前请备份好数据库,以免误操作造成数据的丢失。

在网站根目录下新建一个php文件,并将如下代码放到其中

<?php
require('wp-load.php');
// 替换的关键词和对应的替换词
$replacements = array(
    '关键词1' => '替换词1',
    '关键词2' => '替换词2',
    // 继续添加需要替换的关键词和对应的替换词
);

// 获取所有文章
$args = array(
    'post_type' => 'post',  // 文章类型可以根据实际情况调整
    'posts_per_page' => -1, // 获取所有文章
);
$query = new WP_Query($args);

if ($query->have_posts()) {
    while ($query->have_posts()) {
        $query->the_post();
        $post_id = get_the_ID();
        $post_content = get_post_field('post_content', $post_id);

        // 执行替换操作
        $updated_content = str_replace(array_keys($replacements), array_values($replacements), $post_content);

        // 更新文章内容
        $post_data = array(
            'ID' => $post_id,
            'post_content' => $updated_content,
        );
        wp_update_post($post_data);
    }
    wp_reset_postdata();
} else {
    echo '没有找到文章。';
}
?>

最后访问就可以了,一定要放到网站根目录,因为需要用到WordPress的函数。

THE END