Created
March 27, 2023 09:05
-
-
Save mrizwan47/1d09b834398a4b2cf4a8e75723ebeaa8 to your computer and use it in GitHub Desktop.
Use Python Selenium to Delete bulk delete posts in WordPress (without WP REST API)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from selenium import webdriver | |
from selenium.webdriver.common.keys import Keys | |
from selenium.webdriver.common.by import By | |
from selenium.webdriver.support.ui import WebDriverWait | |
from selenium.webdriver.support import expected_conditions as EC | |
from selenium.webdriver.chrome.service import Service | |
from chromedriver_py import binary_path | |
# Your WordPress credentials | |
username = "your_username" | |
password = "your_password" | |
chrome_options = webdriver.ChromeOptions() | |
chrome_options.add_argument('--headless') | |
chrome_options.add_argument('--no-sandbox') | |
chrome_options.add_argument('--disable-dev-shm-usage') | |
# Initialize the browser | |
browser = webdriver.Chrome(executable_path=binary_path, options=chrome_options) | |
# Log in to WordPress | |
browser.get("https://wpwebsite.com/wp-login.php") | |
browser.find_element(By.ID, "user_login").send_keys(username) | |
browser.find_element(By.ID, "user_pass").send_keys(password) | |
browser.find_element(By.ID, "wp-submit").click() | |
# Wait for the login to complete | |
WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, "wp-admin-bar-my-account"))) | |
# Navigate to the target page | |
browser.get("https://wpwebsite.com/wp-admin/edit.php") | |
# Execute JavaScript to delete posts until there are no more left | |
while True: | |
WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, "cb-select-all-1"))) | |
# Check if there are no more posts | |
if browser.execute_script("return document.querySelectorAll('.wp-list-table .no-items').length > 0;"): | |
break | |
# Run the JavaScript code to delete posts | |
browser.execute_script(""" | |
jQuery('#cb-select-all-1').click(); | |
jQuery('#bulk-action-selector-top').val('trash'); | |
jQuery('#doaction').click(); | |
""") | |
# Wait for the action confirmation message | |
WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "#message.updated.notice"))) | |
# Refresh the page | |
browser.refresh() | |
# Close the browser | |
browser.quit() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment