Skip to content

Instantly share code, notes, and snippets.

@micahjon
Last active January 18, 2024 15:18
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save micahjon/6573f3c8c2424556364250e04a249937 to your computer and use it in GitHub Desktop.
Save micahjon/6573f3c8c2424556364250e04a249937 to your computer and use it in GitHub Desktop.
// ==UserScript==
// @name Convert post to Gutenberg
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Convert Wordpress classic posts to Gutenberg layout
// @author Micah Engle-Eshleman
// @include /^https:\/\/subdomain\.domain\.com\/wp-admin\/post.php\?post=\d+&action=edit/
// @grant none
// ==/UserScript==
/*
The big picture:
The Tampermonky extension runs this code on your Edit Post pages, automatically upgrading them
to Gutenberg, pressing Update, then moving to the next post.
Instructions:
1. Install the Tampermonky extension and add this as a script.
2. Update the @include regex above to match Edit Post pages on your Wordpress site
3. Update getURL function below to return an Edit Post page URL
4. Update postIDs array with all the post IDs that you'd like to convert
You can get all the post IDs in PHP
get_posts(array('fields' => 'ids', 'posts_per_page' => -1));
or by using the REST API, e.g.
/wp-json/wp/v2/posts?per_page=100&_fields[]=id&page=1
/wp-json/wp/v2/posts?per_page=100&_fields[]=id&page=2
...etc
5. Navigate to your Wordpress site, open console in Devtools, enter code:
localStorage.setItem('gutenberg_post_index', 0);
6. Navigate to a post on your Wordpress site and the script should start running and logging progress
7. For the script to work, the Wordpress page needs to be focused. I recommend clicking on the tab
instead of the page content itself, so it doesn't prompt you to confirm leaving the page after each
update and just does so automatically.
You may also want to check "Preserve log" in the DevTools console, so you can see progress for all
posts and loop back to any that failed to convert
*/
(function () {
'use strict';
nextPost(parseInt(localStorage.getItem('gutenberg_post_index')));
//
// 3. Update this URL to match your site
//
function getURL(postID) {
return `https://subdomain.domain.com/wp-admin/post.php?post=${postID}&action=edit`;
}
function nextPost(currentIndex) {
// Get current index from LocalStorage
if (Number.isNaN(currentIndex)) {
console.error('No currentIndex found in LocalStorage')
return;
}
//
// 4. Add your post IDs here
//
const postIDs = [13009, 11640, 10716, 9526, 9504, 9524, 9419, 3522, 3507, 3469, 2906, 2195, 2152];
const postID = postIDs[currentIndex];
if (!postID) {
console.error('No postID for index =', currentIndex);
return;
}
// Never convert same post twice (prevent potential infinite loop in case of redirect)
const lastPost = localStorage.getItem('gutenberg_post_id');
if (lastPost === postID) {
console.error('Already processed this post!')
return;
}
localStorage.setItem('gutenberg_post_index', currentIndex);
localStorage.setItem('gutenberg_post_id', postID);
// Redirect to current post if need be
const url = getURL(postID);
if (url !== window.location.href) {
console.log('Redirecting to post', currentIndex, postID);
window.location.href = url;
return;
}
// Convert post
setTimeout(() => {
convertPost(({ success, error }) => {
if (success) {
console.log(`Converted post ${currentIndex + 1} of ${postIDs.length}`, postID, window.location.href);
} else {
console.error(`Failed to convert post ${currentIndex + 1} of ${postIDs.length}`, postID, window.location.href, error);
}
// Go to next page
nextPost(++currentIndex);
});
}, 3000);
}
function convertPost(callback) {
let toolbar = document.querySelector('.block-library-classic__toolbar.has-advanced-toolbar');
if (!toolbar) return callback({ error: 'no_toolbar' });
// Click toolbar
toolbar.click();
// Page must be focused for toolbar to be accessible.
waitForMenuToggleButton((menuToggleButton) => {
// Click menu toggle button
menuToggleButton.click();
onNextIdleFrame(() => {
const convertToBlocksButton = [...document.querySelectorAll('.block-editor-block-settings-menu__control')]
.find(button => button.textContent === 'Convert to Blocks');
if (!convertToBlocksButton) return callback({ error: 'no_convertToBlocksButton' });
// Click convert to blocks
convertToBlocksButton.click();
// Wait for blocks to render & autosave to complete
setTimeout(() => {
const updateButton = document.querySelector('.editor-post-publish-button');
if (!updateButton) return callback({ error: 'no_convertToBlocksButton' });
// Click Update
updateButton.click();
// Wait for update to complete
setTimeout(() => {
return callback({ success: true });
});
}, 1000);
});
});
}
function waitForMenuToggleButton(callback) {
const menuToggleButton = document.querySelector('.block-editor-block-settings-menu__toggle');
if (menuToggleButton) return callback(menuToggleButton);
console.log('Unable to get toggle button in Post Editor. It may be that Wordpress page is not focused. Maybe try clicking on the tab in your browser.')
setTimeout(() => {
waitForMenuToggleButton(callback);
}, 1000);
}
function onNextIdleFrame(callback) {
requestIdleCallback(() => requestAnimationFrame(callback));
}
})();
@shanzantrik
Copy link

shanzantrik commented May 26, 2022

Hi I have followed the steps mentioned in the gist, however the scripts gets executed till line 98 and after that there is no change in the post, can you please help me with this, I am stuck and I am in a desperate need of help thanks. my email is shantanu.goswami@redcrackle.com

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment