Wordpress, Gutenberg Templates how to add Lables between blocks? - wordpress

I'm forcing a block template for the editor view of a specific custom post type using basically this example as a guide:
https://developer.wordpress.org/block-editor/reference-guides/block-api/block-templates/#locking
function myplugin_register_template() {
$post_type_object = get_post_type_object( 'post' );
$post_type_object->template = array(
array( 'core/paragraph', array(
'placeholder' => 'Add Description...',
) ),
);
$post_type_object->template_lock = 'all';
}
add_action( 'init', 'myplugin_register_template' );
I was able to set multiple input fields and change their default attributes like their placeholder or content.
What I would love is the ability to add a label in the editor above the input field.
The only solution I could find was creating a static block with static text.
Awful.
I would need to create a block for each label.
I would love a way to set its content from the placeholder or content attribute from the above template definition code but, for the life of me, I can't find any documentation on how to go about it.
so the questions are:
is there an easier way to set a static label above each field in a template that I'm missing?
is there a way to implement a label block that takes a content attribute from there?

Yes, using a 3 step approach you can add an extra attribute/s and insert custom content to existing blocks without creating a new block. After the additional attribute is added, you can then set the default value in your custom post template which is then displayed in the Editor, eg:
Step 1: Use Register Block Type Filter to assign a new label attribute to the existing "core/paragraph" block:
plugin.js:
function addLabelAttribute(settings, name) {
if (name !== 'core/paragraph') {
return settings;
}
return lodash.assign({}, settings, {
attributes: lodash.assign({}, settings.attributes, {
label: {
type: 'string',
default: ""
}
})
});
}
wp.hooks.addFilter(
'blocks.registerBlockType',
'core/paragraph',
addLabelAttribute
);
Part 2: Create a Higher Order Component to insert the <label>...<\label> into <BlockEdit> only if a label is set. The value of the label attribute is destructured from the props:
plugin.js
const { createHigherOrderComponent } = wp.compose;
const { useBlockProps } = wp.blockEditor;
const withLabelOutput = createHigherOrderComponent((BlockEdit) => {
return (props) => {
const blockProps = useBlockProps();
const { attributes: { label } } = props;
if (label) {
// Add the custom label within a wrapped <BlockEdit>
return (
<div {...blockProps}>
<label>{label}</label>
<BlockEdit {...props} />
</div>
);
}
// No label set, return default <BlockEdit>
return (<BlockEdit {...props} />)
};
}, 'withLabelOutput');
wp.hooks.addFilter(
'editor.BlockEdit',
'core/paragraph',
withLabelOutput
);
Ref: Block Editor Handbook > Block Filters
Part 3: Set a default value for the new label attribute within the template of the required post/custom post type:
plugin.php:
function myplugin_register_template(){
// N.B. Use a custom post type unless you want this to apply to all posts
$post_type_object = get_post_type_object('post');
$post_type_object->template = array(
array(
'core/paragraph',
array(
'placeholder' => 'Add Description...',
'label' => 'My Custom Label'
)
)
);
$post_type_object->template_lock = 'all';
}
add_action('init', 'myplugin_register_template');
(Optional) Add a your own custom editor style for the <label>, and enqueue it for the editor only, eg:
.wp-block-paragraph label{
font-weight: bold;
border-bottom: 1px solid grey;
padding-bottom: 0.5em;
display:block;
width:100%;
}
All the code example given above can be combined into a plugin, which creates a label in the Editor like:

Related

remove property from wordpress core gutenberg block

With the new wordpress update there are some new properties that have been added to the core gutenberg blocks to make it easier for certain users to customize these blocks
In the image above you can see the example for the new looks of the quote block. For instance there is now the option to change the appearance of the typography as well as a new 'plain' option for the styles. I want to remove these options, but The only thing i have found so far is how to add extra properties nd how to remove the block entierly.
For the styles, i have found the hook to get the property, but I don't know how i can modify this so it doesn't show the "plain" option:
// hide "plain" opiton inside the style tab of the quote block.
const {
addFilter,
} = wp.hooks;
addFilter(
'blocks.registerBlockType',
'jsforwp-advgb/extend-quote-block',
extendBlockQuoteBlock
);
function extendBlockQuoteBlock( settings, name ) {
if ( !settings || !settings.supports ) {
return settings;
}
if ( 'core/quote' !== name ) return settings;
console.log( settings.styles );
return settings;
}
Block styles can be removed with unregisterBlockStyle(blockName, styleVariationName). There is no need extend or add a filter to the block registration, just use unregisterBlockStyle when the DOM is ready to prevent a race condition:
wp.domReady( function () {
wp.blocks.unregisterBlockStyle( 'core/quote', 'plain' );
} );
Ref: Block Editor Handbook / Reference Guides / Block API Reference / Styles
Update: Below is a screenshot showing the effect of running wp.blocks.unregisterBlockStyle( 'core/quote', 'plain' ) in the console.
If you wish to remove typography, it is different to block styles and is from the block supports API, which is done with addFilter and lodash assign to remove support for the features you dont want, eg:
wp.hooks.addFilter(
'blocks.registerBlockType',
'jsforwp-advgb/extend-quote-block',
extendBlockQuoteBlock
);
function extendBlockQuoteBlock(settings, name) {
if (name !== 'core/quote') {
return settings;
}
return lodash.assign({}, settings, {
supports: lodash.assign({}, settings.supports, {
typography: false,
}),
});
}

How to change WP Gutenberg's category components panel?

In Gutenberg Editor, I try to modify the categories panel (the one on the right where I choose the categories my post will be placed into).
One should not be able to add a post to a category if that category has child-categories. As the categories are static, it'll be ok to use the category-id.
My idea was to use the enqueue_block_editor_assets and add some javascript to disable the checkbox via the ID of the element.
This does not work, the element could not be found :-(
This is my unfunctional code so far:
functions.php:
function gutenberg_enqueue()
{
wp_enqueue_script(
'gutenberg-additions-script',
get_stylesheet_directory_uri().'/gutenberg-additions.js',
array(), true, true
);
}
add_action('enqueue_block_editor_assets', 'gutenberg_enqueue', 999);
(I use get_stylesheet_directory_uri(), because I am in a child theme)
gutenberg-additions.js:
window.onload = function () {
var cat1 = document.getElementById('editor-post-taxonomies-hierarchical-term-1');
if (cat1 != null) {
cat1.disabled = true;
}
Welcome to Stackoverflow. There is an example about that in the gutenberg github directory. It is written in the old es5 syntax, but should easily be transferrable to esnext. It uses the editor.PostTaxonomyType filter to edit the taxonomies component.
var el = wp.element.createElement;
function customizeProductTypeSelector( OriginalComponent ) {
return function( props ) {
if ( props.slug === 'product-type' ) {
return el(
'div',
{},
'Product Type Selector'
);
} else {
return el(
OriginalComponent,
props
);
}
}
};
wp.hooks.addFilter(
'editor.PostTaxonomyType',
'my-custom-plugin',
customizeProductTypeSelector
);
If you need more information, also read the comments on this github issue.

Programmatically adding columns in VIEWS

In drupal 7 view, I have created a custom module and add dynamic columns using below method.
function my_module_views_pre_view(&$view, &$display_id, &$args) {
if ($view->name == 'my_view') {
$countries = my_module_vocab_terms('countries');
foreach ($countries as $country){
$view->add_item($view->current_display, 'field', 'views', 'nothing', array(
'label' => $country->name,
'alter' => array('text' => $country->tid),
'element_class' => 'my-field',
'element_default_classes' => 0,
), $country->tid);
}
}
}
}
But the text value repeated in each rows like this.
Please suggest how to pass value for each row.
Thanks
If anyone is still interested how to alter values to such fields.
You can do so by rendering the fields and altering the data in one of the hooks where the results are already fetched eg. the hook_views_post_execute, hook_views_pre_render, hook_views_post_render depending on your needs.
/**
* Implements hook_views_post_execute().
*/
function my_module_views_post_execute(view &$view) {
$view->style_plugin->render_fields($view->result);
$view_fields = &$view->style_plugin->rendered_fields;
foreach ($view_fields as &$field) {
$field['my_field'] = "some value";
}
unset($field);
}

Drupal 8 translating paragraphs programmatically

Paragraphs are supposed to be translated on on the level of their component fields, not on the paragraph_field level. So how do you programmatically translate paragraphs?
To be more explicit, my paragraph field is not translatable, but the component fields are. So how can I load a node, loop through the paragraph items, and add translations to the fields?
Does anyone have an example?
Thanks.
following https://www.flocondetoile.fr/blog/translate-programmatically-drupal-8 node translation:
This is an abstraction of my actual code, and I haven't actually tested it:
$node = node_load(12);
if ($node->hasTranslation('de')) {
$transl_node = $node->getTranslation('de');
foreach ($transl_node->field_paragraph => $paragraph) {
$entity_array = $paragraph->toArray();
$translated_fields = [];
$translated_fields['field_body'] = array(
'value' => 'translated value',
'format' => 'full'
);
$translated_fields['field_section_title'] = 'translated section title';
$translated_entity_array = array_merge($entity_array, $translated_fields);
if (!$paragraph->hasTranslation('de')) {
$paragraph->addTranslation('de', $translated_entity_array);
$paragraph->save();
}
}
$transl_node->save();
}

Add custom style button to wysiwyg in Advanced custom fields

I would like to add a custom button to the wysiwyg editor in Advanced custom fields. I have not found any good solution on how to do it.
What I want is a button that wraps the selected text in <span class="someclass"></span> so that I can style this as I want.
How do I do this?
What you will need to do is tie into your TinyMCE editor buttons. This will add a format dropdown to your WYSIWYG editor for the class. You can then select your text and choose the class from the dropdown. Use text view to check to see if it worked.
/*
* Callback function to filter the MCE settings
*/
// Callback function to insert 'styleselect' into the $buttons array
function my_mce_buttons_2($buttons) {
array_unshift($buttons, 'styleselect');
return $buttons;
}
// Register our callback to the appropriate filter
add_filter('mce_buttons_2', 'my_mce_buttons_2');
function my_mce_before_init_insert_formats($init_array) {
// Define the style_formats array
$style_formats = array(
// Each array child is a format with it's own settings
array(
'title' => 'Some Class',
'inline' => 'span',
'classes' => 'someclass'
),
);
// Insert the array, JSON ENCODED, into 'style_formats'
$init_array['style_formats'] = json_encode($style_formats);
return $init_array;
}
// Attach callback to 'tiny_mce_before_init'
add_filter('tiny_mce_before_init', 'my_mce_before_init_insert_formats');

Resources