Firing Wordpress Gutenberg "Convert to Blocks" programmatically - wordpress

I have several robots, written in Node.js, to auto-generate HTML contents and put them into several Wordpress sites using REST API. Recently Wordpress 5.0 has been officially released, and Gutenberg has become the default editor. All the old posts, as well as those generated by robots, will be encapsulated in a single "Classic" block.
As most of us already know, additional markup should be added to convert the HTML elements into blocks, and there has been a "Convert to Blocks" button to convert them into blocks in Gutenberg UI. Is there any convenient way (say making use of built-in functions) to do the same things as "Convert to Blocks" programmatically, or we should wrap those Gutenberg related markups one by one? Any help should be appreciated

May be this is a little late, but if someone is still looking for a solution here's how you do it.
This code assumes that your classic block is the first one:
var block = wp.data
.select("core/editor")
.getBlocks()[0];
wp.data.dispatch( 'core/editor' ).replaceBlocks(block.clientId, wp.blocks.rawHandler(
{ HTML: wp.blocks.getBlockContent( block ) }
));
If you want to do it for all classic blocks, simply iterate overall blocks and look for block name core/freeform to convert it like this:
wp.data.select("core/editor").getBlocks().forEach(function(block, blockIndex){
if (block.name === "core/freeform"){
wp.data.dispatch( 'core/editor' ).replaceBlocks(block.clientId, wp.blocks.rawHandler(
{ HTML: wp.blocks.getBlockContent( block ) }
));
}
})

Related

Easy Admin Bundle. Trix Editor. Change wrapper tags of code sections. <pre> -> <pre><code>

I'm using the Easy Admin Bundle for a mini Symfony app.
The bundle comes with the trix editor for the text_editor field input.
The editor is pretty cool and offers a code feature that encapsulates the paragraph in <pre> tags. The issue is I'm using highlightjs on frontend to make my code sections pretty. Now highlightjs requires code be encapsulated in <pre><code> ...code here... </code></pre> tags which is a bummer.
Is there any way to control in which tags are code sections encapsulated with the trix editor. In my specific case from <pre> to <pre><code>?
I had the exact same problem, and unfortunately I couldn't figure out how to update the Trix source code to add the code element in the pre element and also add the class. I asked the question here, and I'm going to open an issue to see if the nice folks over at Trix would consider adding this functionality.
So, I put together a little hack that will transform the pre elements when I display them to the user. Here is what the code looks like:
const applyFormattingToPreBlocks = function () {
const preElements = this.showPostBody.querySelector('.trix-content').querySelectorAll('pre');
preElements.forEach(function(preElement) {
const regex = /(?!lang\-\\w\*)lang-\w*\W*/gm;
const codeElement = document.createElement('code');
if (preElement.childNodes.length > 1) {
console.error('<pre> element contained nested inline elements (probably styling) and could not be processed. Please remove them and try again.')
}
let preElementTextNode = preElement.removeChild(preElement.firstChild);
let language = preElementTextNode.textContent.match(regex);
if (language) {
language = language[0].toString().trim();
preElementTextNode.textContent = preElementTextNode.textContent.replace(language, '');
codeElement.classList.add(language, 'line-numbers');
}
codeElement.append(preElementTextNode)
preElement.append(codeElement)
})
};
I also wrote up a blog post that goes into more detail about what this code is doing. I using Rails 6 and the post has an example of what the formatting looks like. Let me know if you have questions.

Extending built in image block of gutenberg editor

I am on wodpress 5.2 with twenty-ten theme. This means there is a lot of places where gutenberg generated content is broken. I could fix many things in child theme css, yet I want embedded images looking like old ones. I am looking for short and clean way to inherit what built-in image block offers and make custom image with same editor options yet slightly modified HTML fragment generated by that block, applying custom classes to figure and figcaption for a start.
You have two options (at least).
Make your own block
You can grab the code of the image block at github and start creating your own block from it, e.g. using create-guten-block. You will need some time (~ 1-2h) to get it working because some import statements and other things must be adapted, it's not only copy and past.
=> Use it if you need lots of customizations to what the image block can offer and you want to get to the heart of block creation, altering functions, behavior, appearance, anything.
Edit the existing block in a filter
Gutenberg offers many new filters, e.g. the blocks.getSaveContent.extraProps filter. It lets you manipulate the blocks properties, such as the classes.
function addBlockClassName( props, blockType ) {
if(blockType.name === 'core/image') {
return Object.assign( props, { class: 'wp-caption' } );
}
return props;
}
wp.hooks.addFilter(
'blocks.getSaveContent.extraProps',
'some-custom-name/add-block-class-name',
addBlockClassName
);

Efficiently reusing (poorly designed) JSON template for additional sites?

My supervisor just handed me a pile of JSON files from a freelancer which we are going to use to make multiple (similar) websites. Lucky me, I'll get to be the one updating the content and css for the different versions.
This is my first time working with JSON, so while I can't be sure that this is a poorly designed template, the fact that the css is very messy (in order to change the color of buttons throughout the site from yellow to orange, at least 15 different classes need to be adjusted, which seems to me to defeat the whole purpose of css...) doesn't give me hope.
I've brute-forced my way through the first two different sites, but since it looks like we'll be doing a lot more of them, I'm looking for ways to streamline the process (in particular making sure to change the content in all the places the content needs changing, which is a lot of files, with different content for different versions).
I'm personally old-school enough to like awk (well, that, and it's what I'm most used to programming in), so my backup plan is to just set up an awk/batch script or two which will take in a "these are the bits of info that go in these specific places" file and update all the relevant files. However, I'm sure there's a better way to do this, which is why I'm turning to y'all.
Is there anything that already exists for streamlining processes like these? Or a coding system/language that's well-suited to this project? A GUI which I can connect to bits of text that need changing?
Ideally, I'd like to set up something that even a monkey (or a non-caffeinated me) could use as often as needed. I'm already going to have to dive into the source code to clean it up (because, gasp, we might need to be able to have more than 5 people on the "our team" page, for example - without bad css/html workarounds), so making other tweaks that'll help with the content update process can happen en route.
I have recently used underscore to render templates from JSON. this is a front end tool, but you could automate it with some backend tools (a simple cURL or file_get_content in php will do).
Here is a link to a tutorial
your template will be a JavaScript template in your html file:
<div id="rendered"></div>
<script type="text/template" class="template">
<%- rc.listTitle %>
</script>
and in your JavaScript code you load:
<script type="text/javascript">
// When rending an underscore template, we want top-level
// variables to be referenced as part of an object. For
// technical reasons (scope-chain search), this speeds up
// rendering; however, more importantly, this also allows our
// templates to look / feel more like our server-side
// templates that use the rc (Request Context / Colletion) in
// order to render their markup.
_.templateSettings.variable = "rc";
// Grab the HTML out of our template tag and pre-compile it.
var template = _.template(
$( "script.template" ).html()
);
// Define our render data (to be put into the "rc" variable).
var templateData = {
listTitle: "Olympic Volleyball Players",
};
// Render the underscore template and inject it after the div rendered
// in our current DOM.
$( "#rendered" ).after(
template( templateData )
);
</script>

How can I strip html and word formatted text from a text box

I have a multiline textbox, need to restrict users from adding html input, any other scripts, copy pasting from word or any other word processer.
But I need to allow bullets for the input.
I thought it would be a simple thing to do since it looks like a common problem.
But I could not find a good solution in the web, please help.
I am using telerik tool kit as well.
If you need to strip out HTML then HTML Agility Pack is your friend. It will deal with all manner of malformed html. As a bonus it is included in Sitecore already.
If you want to use something with a friendlier syntax then consider CSQuery or Fizzler both of which provide you with a jQuery type syntax from within C#.
If you need to build a whitelist then take a look at this post on how to add whitelist:
public void RemoveNotInWhiteList(HtmlNode pNode, IEnumerable<string> pWhiteList)
{
if (!pWhiteList.Contains(pNode.Name))
{
pNode.Remove();
return;
}
pNode.Attributes
.Where(att => !pWhiteList.Contains(att.Name))
.ToList()
.ForEach(att => att.Remove());
pNode.ChildNodes
.ToList()
.ForEach(att => RemoveNotInWhiteList(att, pWhiteList));
}
You could create a Validation rule, I reckon (in /sitecore/System/Settings/Validation Rules). Put the allowed HTML in a whitelist somewhere (possibly a Sitecore item), when validating run through that whitelist. If any other HTML tags appear in it, make it invalid.
This doesn't stop them from putting it in, but it will stop the item from being published.
You could even create a custom item:saved event handler which strips out all HTML tags apart from the whitelisted stuff. Again, it doesn't stop them from putting the HTML tags in, but as soon as the item is saved it will be removed. Going even a step further than this, I think it also would be possible to use the Rules Engine for this - this article by John West shows how to use the Rules engine to modify item names, but you could modify it to read out specific text boxes.
Neither option here will stop users from inputting HTML, but the HTML tags will automatically be removed when the item is saved.

HTML\rich text in Drupal's node title?

I need the node titles to be able to display some text formatting.
As far as I understand, Drupal's title field is just plain text, it doesn't allow HTML or any other input format. Is that true? Is there a way to override this, or another solution?
I am working with Drupal 6.
You can pretty easily do this in your theme, there are different ways to do with. The simplest would probably to do it in your template.php
/* this function generates the variables that are available in your node.tpl,
* you should already have this in your template.php, but if not create it
*/
function mytheme_preprocess_node(&$vars) {
// It's important to run some kind of filter on the title so users can't
// use fx script tags to inject js or do nasty things.
$vars['title'] = filter_xss($vars['node']->title);
}
What happens in the function is that it overwrites the default value for $title in the node.tpl which holds the variable used for the title. It is usually placed within a h1 or h2 tag, so you should be aware of that. The filter_xss is used to only allow basic html tags, so protect the site, you can look at that function here. That are some other filter functions, like check_markup, and filter_xss_admin, but you can give a second param for filter_xss which is an array of allowed tags, so should the default not be good enough, you can just change it to fit your needs.
Use function mytheme_preprocess_page for D7.
Extending the module mentioned by wiifm, for D7 there is now also: https://drupal.org/project/html_title_trash
It allows more tags and also works for block titles, rather than just node titles.

Resources