2025-03-17(월) using wp-cli for sync and replace database.
import subprocess import shlex import os def wp_search_replace(old_url, new_url, wp_path, table_prefix=None): """ Execute wp-cli search-replace command safely Args: old_url: Original URL to search for new_url: New URL to replace with wp_path: Path to WordPress installation table_prefix: Optional WordPress table prefix """ try: # Sanitize inputs using shlex.quote to prevent command injection old_url = shlex.quote(old_url) new_url = shlex.quote(new_url) wp_path = shlex.quote(wp_path) # Base command command = [ 'wp', 'search-replace', old_url, new_url, '--path=' + wp_path, '--skip-columns=guid' ] # Add table prefix if specified if table_prefix: command.append(f'--prefix={shlex.quote(table_prefix)}') # Execute command using subprocess with proper security measures result = subprocess.run( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True ) print("Search and replace completed successfully:") print(result.stdout) return True except subprocess.CalledProcessError as e: print(f"Error executing wp-cli command: {e}") print(f"Error output: {e.stderr}") return False except Exception as e: print(f"An unexpected error occurred: {e}") return False # Example usage if __name__ == "__main__": # Example parameters OLD_SITE_URL = "http://old-site.com" NEW_SITE_URL = "http://new-site.com" WP_PATH = "/var/www/html/wordpress" # Execute search-replace wp_search_replace( old_url=OLD_SITE_URL, new_url=NEW_SITE_URL, wp_path=WP_PATH )