WordPress, 實用技巧

清除 WPBakery Page Builder 短碼

清除 WPBakery Page Builder 短碼

遲早都要面對的 WPBakery Page Builder 短碼問題

WPBakery Page Builder 是一款廣受歡迎的 WordPress 區塊編輯器。然而,隨著時間的推移,在 2021 年後的 Elementor 的強勢崛起,許多過去舊的採用 WPBakery Page Builder 佈景主題會面臨改版後功能失效、樣式跑版等等問題,在進行轉換改版時會碰到一個大鐵板,幾乎用區塊編輯器做的頁面與文章都會因為你停用外掛後,整個噴出大量的短碼無法解譯,會積累大量的 WPBakery Page Builder 產生的短碼,這些短碼可能會影響您網站的性能和內容的清晰度。在這篇文章中,我將分享一個有效的方法來清除這些不必要的短碼。

完整程式碼

首先,讓我們來看看如何使用自訂函數來移除這些短碼。以下是我們將要使用的程式碼:

function uni_remove_vc_shortcodes_from_database() {
    // 取得所有文章
    $args = array(
        'post_type' => 'any',
        'posts_per_page' => -1,
    );
    $posts = get_posts($args);

    // 遍歷所有文章
    foreach ($posts as $post) {
        $content = $post->post_content;
        $content = uni_remove_vc_shortcodes($content);
        wp_update_post(array(
            'ID' => $post->ID,
            'post_content' => $content,
        ));
    }
}
add_action('admin_init', 'uni_remove_vc_shortcodes_from_database');

此程式碼的運作原理如下:

  1. 透過 get_posts 函數取得所有文章。
  2. 遍歷每篇文章,並對其內容進行處理。
  3. 調用 uni_remove_vc_shortcodes 函數來清除短碼。
  4. 透過 wp_update_post 函數更新文章內容。

關鍵清除程式碼

接著再放入下面 uni_remove_vc_shortcodes 程式碼函數:

function uni_remove_vc_shortcodes($content) {
$pattern = '/\[\/?vc_[^\]]*]/';
$replacement = '';
$content = preg_replace($pattern, $replacement, $content);
return $content;
}
add_filter('the_content', 'uni_remove_vc_shortcodes', 999);

此函數使用正則表達式來搜尋和移除所有以 [vc_[/vc_ 開頭的短碼,並將其替換為空字串。

這個方法可以大幅提升您網站的載入速度和內容的清晰度。當您的網站不再依賴 WPBakery Page Builder 時,這種短碼清理方法尤其有用。此外,這個過程可以通過 add_action('admin_init', 'uni_remove_vc_shortcodes_from_database') 自動在後台初始化時執行,方便您管理和維護網站。切記!此程式碼只需要執行一次,如果要清除類似短碼變種,例如 Ronneby 這佈景主題,他是用 RC 開頭的,你就只需要變更 [vc_ 變成 [rc_ 以此類推,詳細正確具體一定要進入要清除的網站查看短碼怎麼命名使用的。

2024/11/23 更新高效版本

因為之前的版本要重複執行幾次,感覺不是很高效率,因此提供新版的加入 Metadata 檢查是否重複的處理

function uni_remove_vc_shortcodes_from_database() {
    $batch_size = 100; // 每次處理的文章數量
    $paged = 1;

    do {
        $args = array(
            'post_type' => 'any',
            'posts_per_page' => $batch_size,
            'paged' => $paged,
            'meta_query' => array(
                array(
                    'key' => '_vc_shortcodes_removed',
                    'compare' => 'NOT EXISTS',
                ),
            ),
        );
        $posts = get_posts($args);

        foreach ($posts as $post) {
            $content = $post->post_content;
            $new_content = uni_remove_vc_shortcodes($content);

            if ($new_content !== $content) {
                wp_update_post(array(
                    'ID' => $post->ID,
                    'post_content' => $new_content,
                ));
            }

            // 標記文章已被處理
            update_post_meta($post->ID, '_vc_shortcodes_removed', 1);
        }

        $paged++;
    } while (count($posts) > 0);
}
add_action('admin_init', 'uni_remove_vc_shortcodes_from_database');