Extending built in image block of gutenberg editor - wordpress

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
);

Related

Firing Wordpress Gutenberg "Convert to Blocks" programmatically

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 ) }
));
}
})

changing body classes based on page tpl.php template

I haven't quite the right process to change the body classes based on the page being viewed.
I have about 20 or so pages within a subsection that all have a different background color and reversed nav links from the main site.
I can't figure out if there is some kind of preprocess function to use (and which) in template.php or if I should do something specifically in the certain xx-page.tpl.php file.
Just adding an ID to the body tag in the xx-page.tpl.php isn't reliable due to browser caching.
I've seen this snippet:
if (drupal_is_front_page()) {
$vars['body_class'] .= ' home';
}
however, "is it the front or not" isn't enough because it's also not just a page, it's a specific page but I've either missed the syntax or am doing something wrong.
Is this a case where I need to create a custom function and if so, is the template.php page where it goes?
also, I'm in Drupal 6.26
Thanks
Are you looking for this function?
http://api.drupal.org/api/drupal/includes!theme.inc/function/template_preprocess_page/6
You might also want to have a look at the Context module.

Custom content type with field that creates its own CSS?

I'm looking to create a content type which includes a field for an image file - simple enough. However, I want this image file to be displayed as a background-image. Do I have to create a custom node.tpl and include the image source in an inline style="background: url(sites/all/themes/theme/images/image.png);", or is there a more elegant way to do this, possibly including writing to a stylesheet from the field using JavaScript?
You can use drupal_add_css in a hook_node_view function, node preprocess script, or node template to add a style directly:
$css = "#bg-img {
background: url(/sites/all/themes/theme/images/image.png) left top no-repeat;
};"
drupal_add_css($css, 'inline');
Or, you can use a drupal setting and then reference it in a jquery script; look up drupal_add_js usage & examples with the 'setting' option:
drupal_add_js(array("moduleName" => array('bgImg' => $absolute_url)), 'setting');
Reference in jQuery using Drupal.settings.moduleName['bgImg']
IMO adjusting the node.tpl.php as you describe is perfectly sensible. Using drupal_add_css will let you set a background image on an element outside the node, eg the entire page. I've used jquery when I've needed more advanced positioning/resizing options.
Instead of reading documentations and digging into codes, just use Field Formatter CSS module (https://drupal.org/project/field_formatter_class) and get it done in minutes. It's a gem that you will find yourself using it over and over. It lets you add css classes and other options to each field in the "Manage display" of your custom content type. As for this particular case of serving a user-uploaded image as background, here is a screen capture. Add a class into the Field Formatter Class field, and then you should be able to reposition and resize further with css and jquery.

User defined CSS / Styles

We are looking into providing users of our application the ability override the default site CSS.
Currently they can choose a site theme but it would be nice to allow them to change properties such as background color, font color, font face etc.
I'm torn between giving each site a "user defined" stylesheet that can be edited from the administration area or providing some kind of CSS builder.
The first option provides the most flexibility but could also be the most problematic and requires the user to have some basic understanding of CSS.
So aside from the obvious, (which is the best solution?) I have a few additional questions:
User Defined Css:
Is there a web based CSS editor available?
Is there a server side (.net) CSS validator available (for verifying the css the user enters)
Css Builder:
Is there a web based CSS builder already available?
What is the best way of generating the CSS based on the rules provided by the user (I thought about using some kind of templating engine to do this (NVelocity, Razor etc.)?
Thanks
Solution
I've added an answer below with the solution we went for.
however never used, recently I looked at Brosho Design in the Browser jQuery Plugin
With this Plugin you can style your
markup right in your browser with a
build-in element selector and CSS
editor. Generate the CSS code of
altered elements with one click and
use it in your own stylesheet.
demo here
I'd recommend to build a custom css editor since it's the easiest way to limit which elements and attributes the user will be able to edit / customize, and how. Just keep it simple and you will do just fine.
To validate CSS you could use the API of the W3 CSS Validator, http://jigsaw.w3.org/css-validator/api.html
I've built an application that does exactly this. It's a little more involved as there are multiple master pages and themes, and the user can attach custom urls to load themes - example: /someclienturl would load a specific theme.
Anyway, here's the schema I used. One thing I wish I added is the ability for power users to add custom styles to the stylesheet that's eventually written. Basically, a theme section would apply to a selector #header, for example. And ThemeSectionCssStyle holds user added customizations for that selector. If you have any more questions let me know. It ended up being a fairly involved sub-project. I'm curious to see what anyone else came up with.
I think the key factor here is whether you want your users to 'play with the codez'
If you do then something like this (posted by #Caspar) can be helpful in generating the css. If you do allow direct access to the css then the W3 CSS Validator (posted by #Trikks) is definitely necessary.
In my case I didn't want to provide direct access to the Css. Looking around at various sites that allow you to change simple style properties (background-color, font-face, color etc.) it seems that they have just created their own interfaces for this. There are plenty of javascript plugins around for making this process quite slick (color pickers etc.).
Once you have the styles stored somewhere you need some way of rendering them out.
I couldn't find any .net Css writers. I think it may be possible in Less but the solution was quite simple just using what's built into asp.net mvc.
I created a Css action result (courtesy of #Darin Dimitrov):
public class CssResult : PartialViewResult {
public override void ExecuteResult(ControllerContext context) {
context.HttpContext.Response.ContentType = "text/css";
base.ExecuteResult(context);
}
}
Then in my controller (a simple example):
[HttpGet]
public ActionResult Index()
{
var styles = new Dictionary<string, string>()
{
{ "color", "red" },
{ "font-family", "Consolas, Courier, Serif" },
{ "font-size" , "12px" }
};
return this.Css(styles);
}
Then my view (views/css/index.cshtml):
body {#foreach (var item in Model) {
#string.Format("{0}: {1};", item.Key, item.Value)
}
}
This will essentially render out the styles in the passed in dictionary. Of course you may want to create a specific class for holding these styles so that you could also specify the dom element name/class/id.
Finally to render out the stylesheet on our page we can call Url.Action("index", "css").

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