Skip to content

Instantly share code, notes, and snippets.

@kuroisuna
Created June 11, 2016 05:04
Show Gist options
  • Save kuroisuna/71ef70e3ae9d62df454f2df677275356 to your computer and use it in GitHub Desktop.
Save kuroisuna/71ef70e3ae9d62df454f2df677275356 to your computer and use it in GitHub Desktop.
Translate HTML list into Wordpress' ACF
// Get Ingredients
window.ingredientsContainer = jQuery('.acf-field[data-name=ingredients]');
window.editorContainer = jQuery("#wp-content-editor-container iframe").contents().find("body").get(0);
// Set time hold
window.timeHold = 3;
if (!window.editorContainer) {
console.error('TinyMCE is not here :(');
}
var ingredientsText = window.editorContainer.innerText.trim();
console.log(ingredientsText)
var ingredients = ingredientsText.split("\n").reverse();
// Remove post content
window.editorContainer = jQuery("#wp-content-editor-container iframe")
.contents()
.find("body")
.find("*")
.remove()
.end();
// Extract excerpt
var excerptText = jQuery('#excerpt').val().replace(/\n+/g, '<br>');
// Fill content
window.editorContainer.html(excerptText)
var parts = /([½|¼|¾|\d]+[\/\d ]+(?:(?:lb|l|kg)\b)?)/;
// Remove all rows
setTimeout(removeAllRows, window.timeHold * 1000);
ingredients.forEach(function(ingredient) {
if (!ingredient) {
return;
}
var amountMatches = ingredient.match(parts);
var amount = ((amountMatches && amountMatches[1]) || '').trim();
var ingredientName = ingredient.replace(parts, '').trim();
if (ingredientName.split(" ")[0] != 'de') {
ingredientName = ingredientName[0].toUpperCase() + ingredientName.slice(1);
}
// Add row
setTimeout(function() {
addRow(ingredientName, amount);
}, window.timeHold * 3000);
window.timeHold += 4;
});
function removeAllRows() {
window.ingredientsContainer
.find("[data-event=remove-row]")
.filter(":visible")
.each(function() {
this.click()
})
}
function addRow(ingredient, amount) {
// console.log("Adding: " + ingredient + ", " + amount);
window.ingredientsContainer
.find("[data-event=add-row]")
.get(0)
.click();
var row = window.ingredientsContainer.find("tbody tr:visible:first");
setTimeout(function () {
fillLastRow(row, ingredient, amount);
}, 1000);
}
function fillLastRow(row, ingredient, amount) {
row.find("[data-name=add]").get(0).click();
setTimeout(function() {
jQuery("#acf-popup").find("#term_name").val(ingredient);
jQuery("#acf-popup").find(":submit").get(0).click();
setTimeout(function() {
jQuery("#acf-popup").find(".acf-close-popup").get(0).click();
row.find("td:eq(3) :text").val(amount);
var select2Input = row.find("td:eq(1) input:hidden");
select2Input.data("select2").opts.selectOnBlur = true;
var isDuplicate = select2Input.select2("val").trim();
if (!isDuplicate) {
select2Input.select2("search", ingredient);
setTimeout(function() {
jQuery('#select2-drop-mask').click()
}, 4000);
}
}, 3500);
}, 2000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment