Add Custom Button to TinyMCE in WordPress - wordpress

I want to add a new button with popup to TinyMCE. But i never see the button. I probably are doing wrong this modification. How to insert the new button on that TinyMCE Code?
I have this TinyMCE Code for showing in Wordpress Front-End:
$qt = '';
if( $this->options[ 'wpcc_edit_in_html' ] ) $qt = array( 'buttons' => 'strong,em,block,del,ul,ol,li,spell,close' );
else {
$qt = FALSE;
add_filter( 'wp_default_editor', create_function( '', 'return "tinymce";' ) ); // force visual editor
}
$editor_settings = array(
'theme_advanced_blockformats' => array( 'h2','h3','p' ),
'wpautop' => true,
'media_buttons' => false,
'tinymce' => array(
'theme_advanced_buttons1' => 'bold,italic,blockquote,strikethrough,bullist,numlist,spellchecker,|,undo,redo,|,mygallery_button',
'theme_advanced_buttons2' => '',
'theme_advanced_buttons3' => '',
'theme_advanced_buttons4' => ''
),
'quicktags' => $qt
);
And this one to insert new button:
function filter_mce_button( $buttons ) {
// add a separation before our button, here our button's id is "mygallery_button"
array_push( $buttons, '|', 'mygallery_button' );
return $buttons;
}
function filter_mce_plugin( $plugins ) {
// this plugin file will work the magic of our button
$plugins['myplugin'] = plugin_dir_url( __FILE__ ) . 'mygallery_plugin.js';
return $plugins;
}
add_filter( 'mce_buttons', array( $this, 'filter_mce_button' ) );
add_filter( 'mce_external_plugins', array( $this, 'filter_mce_plugin' ) );

Read this tutorial. https://www.gavick.com/magazine/adding-your-own-buttons-in-tinymce-4-editor.html#tc-section-4
Very detailed tutorial. But the bare essentials are as follows: in your functions.php add this code to register and create your button:
function add_container_button() {
if ( ! current_user_can('edit_posts') && ! current_user_can('edit_pages') )
return;
if ( get_user_option('rich_editing') == 'true') {
add_filter('mce_external_plugins', 'add_container_plugin');
add_filter('mce_buttons_3', 'register_container_button');
}
}
add_action('init', 'add_container_button');
function register_container_button($buttons) {
array_push($buttons, "|", "skizzar_container");
return $buttons;
}
function add_container_plugin($plugin_array) {
$plugin_array['skizzar_container'] = plugin_dir_url( __FILE__ ) . 'shortcodes-js/container.js';;
return $plugin_array;
}
Then you'll need to create a js file which handles how the buttons acts in the editor (you can see mine is referenced in the code above as container.js. Here is the code of my js file:
(function() {
tinymce.PluginManager.add('skizzar_container', function( editor, url ) {
editor.addButton( 'skizzar_container', {
title: 'Add a Container',
icon: 'icon dashicons-media-text',
onclick: function() {
editor.windowManager.open( {
title: 'Container',
body: [{
type: 'listbox',
name: 'style',
label: 'Style',
'values': [
{text: 'Clear', value: 'clear'},
{text: 'White', value: 'white'},
{text: 'Colour 1', value: 'colour1'},
{text: 'Colour 2', value: 'colour2'},
{text: 'Colour 3', value: 'colour3'},
]
}],
onsubmit: function( e ) {
editor.insertContent( '[container style="' + e.data.style + '"]<br /><br />[/container]');
}
});
}
});
});
})();
This creates a popup with a dropdown menu where the user can select a style. Hope this helps in some way

Related

Add "insert button" on toolbar tinymce editor

I want to add an "insert button" on my toolbar tinymce editor.
An example of what I want :
An example of what I want
With the toolbar button, I would like to create a button in my editor and change its style. (Like the gutenberg editor does)
gutenberg editor
To use the tinymce editor, I have this code :
function wpc_boutons_tinymce($buttons) {
$buttons[] = 'underline';
$buttons[] = 'fontselect';
$buttons[] = 'fontsizeselect';
$buttons[] = 'edit-block';
return $buttons;
}
add_filter("mce_buttons_3", "wpc_boutons_tinymce");
$content = '';
$editor_id = 'mycustomeditor';
$settings = array(
'wpautop' => false,
'media_buttons' => false,
'quicktags' => array(
'buttons' => 'strong,em,del,ul,ol,li,block,close'
),
);
wp_editor( $content, $editor_id, $settings );
I didn't find how to do, can you help me ?
Here is my implemented code Follow the step
Paste the code in your theme functions.php
add_action( 'init', 'wptuts_buttons' );
function wptuts_buttons() {
add_filter( "mce_external_plugins", "wptuts_add_buttons" );
add_filter( 'mce_buttons', 'wptuts_register_buttons' );
}
function wptuts_add_buttons( $plugin_array ) {
$plugin_array['wptuts'] = get_template_directory_uri() . '/wptuts-editor-buttons/wptuts-plugin.js';
return $plugin_array;
}
function wptuts_register_buttons( $buttons ) {
array_push( $buttons, 'dropcap', 'showrecent' ); // dropcap', 'recentposts
return $buttons;
}
require( 'wptuts-editor-buttons/wptuts.php' );
Create a folder in your theme root file named wptuts-editor-buttons
Then create a file in wptuts-editor-buttons named wptuts.php and paste the code
<?php
add_shortcode( 'recent-posts', 'wptuts_recent_posts' );
function wptuts_recent_posts( $atts ) {
extract( shortcode_atts( array(
'numbers' => '5',
), $atts ) );
$rposts = new WP_Query( array( 'posts_per_page' => $numbers, 'orderby' => 'date' ) );
if ( $rposts->have_posts() ) {
$html = '<h3>Recent Posts</h3><ul class="recent-posts">';
while( $rposts->have_posts() ) {
$rposts->the_post();
$html .= sprintf(
'<li>%s</li>',
get_permalink($rposts->post->ID),
get_the_title(),
get_the_title()
);
}
$html .= '</ul>';
}
wp_reset_query();
return $html;
}
Also, You need to create a js file in wptuts-editor-buttons > wptuts-plugin.js and paste the code
(function() {
tinymce.create('tinymce.plugins.Wptuts', {
init : function(ed, url) {
ed.addButton('dropcap', {
title : 'DropCap',
cmd : 'dropcap',
image : url + '/dropcap.jpg'
});
ed.addButton('showrecent', {
title : 'Add recent posts shortcode',
cmd : 'showrecent',
image : url + '/images.jpg'
});
ed.addCommand('dropcap', function() {
var selected_text = ed.selection.getContent();
var return_text = '';
return_text = '<span class="dropcap">' + selected_text + '</span>';
ed.execCommand('mceInsertContent', 0, return_text);
});
ed.addCommand('showrecent', function() {
var number = prompt("How many posts you want to show ? "),
shortcode;
if (number !== null) {
number = parseInt(number);
if (number > 0 && number <= 20) {
shortcode = '[recent-post number="' + number + '"/]';
ed.execCommand('mceInsertContent', 0, shortcode);
}
else {
alert("The number value is invalid. It should be from 0 to 20.");
}
}
});
},
// ... Hidden code
});
// Register plugin
tinymce.PluginManager.add( 'wptuts', tinymce.plugins.Wptuts );
})();
Whole the Solution I followed the article
https://code.tutsplus.com/tutorials/guide-to-creating-your-own-wordpress-editor-buttons--wp-30182

How to create multiple meta fields in gutenberg block

I need to create a wordpress Gutenberg block that will allow me to insert some data as name and surname, company name, the best sentence from the references.
So far I managed to create a Gutenberg block that is saving one text field.
dc-references-block.php
// register custom meta tag field
function dcr_register_post_meta() {
register_post_meta( 'page', 'dc_references_block_field', array(
'show_in_rest' => true,
'single' => true,
'type' => 'string',
) );
}
add_action( 'init', 'dcr_register_post_meta' );
function dcr_enqueue() {
wp_enqueue_script(
'dc-references-block-script',
plugins_url( 'dc-references-block.js', __FILE__ ),
array( 'wp-blocks', 'wp-element', 'wp-components' )
);
}
add_action( 'enqueue_block_editor_assets', 'dcr_enqueue' );
dc-references-block.js
( function( wp ) {
var el = wp.element.createElement;
var registerBlockType = wp.blocks.registerBlockType;
var TextControl = wp.components.TextControl;
registerBlockType( 'dc-references-block/dc-references-block', {
title: 'Title',
icon: 'edit',
category: 'common',
attributes: {
blockValue: {
type: 'string',
source: 'meta',
meta: 'dc_references_block_field'
}
},
edit: function( props ) {
var className = props.className;
var setAttributes = props.setAttributes;
function updateBlockValue( blockValue ) {
setAttributes({ blockValue });
}
return el(
'div',
{ className: className },
el( TextControl, {
label: 'write here name of company',
value: props.attributes.blockValue,
onChange: updateBlockValue
}
)
);
},
save: function() {
return null;
}
} );
} )( window.wp );
Whenever I try to add a second text field or textarea to the block I get an error "site does not support this block".
Could anyone explain to me how to, in this situation, add correctly more then one text field and textarea to a block?
It would be better if you included the code that did not work. In any case, I changed your code by adding another text input and a textarea (with relevant entries in attributes and meta).
Here is the modified code. Also, I have changed some of the code to be more readable.
Javascript
( function( wp ) {
const el = wp.element.createElement;
const registerBlockType = wp.blocks.registerBlockType;
const TextControl = wp.components.TextControl;
const TextareaControl = wp.components.TextareaControl;
registerBlockType( 'dc-references-block/dc-references-block', {
title: 'Title',
icon: 'edit',
category: 'common',
attributes: {
blockValue: {
type: 'string',
source: 'meta',
meta: 'dc_references_block_field'
},
// Add two new attributes
name: {
type: 'string',
source: 'meta',
meta: 'dc_references_block_field_name'
},
desc: {
type: 'string',
source: 'meta',
meta: 'dc_references_block_field_desc'
}
},
edit: function( props ) {
const className = props.className;
const setAttributes = props.setAttributes;
// Original element with onChange event as an anonymous function
const text = el( TextControl, {
label: 'write here name of company',
value: props.attributes.blockValue,
key: 'companyName',
onChange: function( value ) {
setAttributes( { name: value } );
}
} );
//Add two new elements
const secondText = el( TextControl, {
label: 'Write your name',
value: props.attributes.name,
key: 'username',
onChange: function( value ) {
setAttributes( { name: value } );
}
} );
const textArea = el( TextareaControl, {
label: 'Write a description',
value: props.attributes.desc,
key: 'desc',
onChange: function( value ) {
setAttributes( { desc: value } );
}
} );
return el(
'div',
{ className: className },
// Children of the main div as an array
[ text, secondText, textArea ]
);
},
save: function() {
return null;
}
} );
}( window.wp ) );
PHP
register_post_meta( 'page', 'dc_references_block_field', array(
'show_in_rest' => true,
'single' => true,
'type' => 'string',
) );
// register two new meta corresponding to attributes in JS
register_post_meta( 'page', 'dc_references_block_field_name', array(
'show_in_rest' => true,
'single' => true,
'type' => 'string',
) );
register_post_meta( 'page', 'dc_references_block_field_desc', array(
'show_in_rest' => true,
'single' => true,
'type' => 'string',
) );

How can I add panels to the sidebar on the Document tab in Gutenberg? [duplicate]

I am trying to add a new component panel under document tab, like categories, featured image etc.
They've added the PluginDocumentSettingPanel SlotFill now.
const { registerPlugin } = wp.plugins
const { PluginDocumentSettingPanel } = wp.editPost
const PluginDocumentSettingPanelDemo = () => (
<PluginDocumentSettingPanel
name="custom-panel"
title="Custom Panel"
className="custom-panel"
>
Custom Panel Contents
</PluginDocumentSettingPanel>
)
registerPlugin('plugin-document-setting-panel-demo', {
render: PluginDocumentSettingPanelDemo
})
add_meta_box will do the trick, but only if you add the context-argument with a value of 'side':
add_meta_box(
'box-id-here',
'Box Title Here',
'createBoxHtml',
'post',
'side' ); // <-- this is important
Arrrh, two days for nothing!
Old answer
According to this tutorial, we can add our custom sidebar and fill it with customized form inputs.
Here is a working example in a React JSX version. This adds a meta field country:
const { registerPlugin } = wp.plugins;
const { PluginSidebar } = wp.editPost;
const { TextControl } = wp.components;
const { withSelect, withDispatch } = wp.data;
// Customized TextControl
const CustomMetaField = withDispatch( ( dispatch, props ) => {
return {
updateMetaValue: ( v ) => {
dispatch( 'core/editor' ).editPost( {
meta: {
[ props.metaFieldName ]: v
}
});
}
};
})( withSelect( ( select, props ) => {
return {
[ props.metaFieldName ]: select( 'core/editor' ).getEditedPostAttribute( 'meta' )[ props.metaFieldName ]
};
} )( ( props ) => (
<TextControl
value={props[ props.metaFieldName ] }
label="Country"
onChange={( v ) => {
props.updateMetaValue( v );
}}
/> )
) );
// Our custom sidebar
registerPlugin( 'custom-sidebar', {
render() {
return (
<PluginSidebar
name="project-meta-sidebar"
title="Project Meta">
<div className="plugin-sidebar-content">
<CustomMetaField metaFieldName="country" />
</div>
</PluginSidebar>
);
},
} );
And in PHP, register the meta field in the init-hook:
register_meta( 'post', 'country', [
'show_in_rest' => TRUE,
'single' => TRUE,
'type' => 'string'
] );
I know:
This is still not the required solution, but nearly.
You can now use the newer useSelect and useDispatch custom hooks. They are similar to withSelect and withDispatch, but utilize custom hooks from React 16.8 for a slightly more concise dev experience:
(Also, using #wordpress/scripts, so the imports are from the npm packages instead of the wp object directly, but either would work.)
import { __ } from '#wordpress/i18n';
import { useSelect, useDispatch } from '#wordpress/data';
import { PluginDocumentSettingPanel } from '#wordpress/edit-post';
import { TextControl } from '#wordpress/components';
const TextController = (props) => {
const meta = useSelect(
(select) =>
select('core/editor').getEditedPostAttribute('meta')['_myprefix_text_metafield']
);
const { editPost } = useDispatch('core/editor');
return (
<TextControl
label={__("Text Meta", "textdomain")}
value={meta}
onChange={(value) => editPost({ meta: { _myprefix_text_metafield: value } })}
/>
);
};
const PluginDocumentSettingPanelDemo = () => {
return (
<PluginDocumentSettingPanel
name="custom-panel"
title="Custom Panel"
className="custom-panel"
>
<TextController />
</PluginDocumentSettingPanel>
);
};
export default PluginDocumentSettingPanelDemo;
Along with registering your meta field as usual:
function myprefix_register_meta()
{
register_post_meta('post', '_myprefix_text_metafield', array(
'show_in_rest' => true,
'type' => 'string',
'single' => true,
'sanitize_callback' => 'sanitize_text_field',
'auth_callback' => function () {
return current_user_can('edit_posts');
}
));
}
add_action('init', 'myprefix_register_meta');
And make sure if using for a custom post type, that you include custom-fields in the array of supports:
'supports' => array('title', 'editor', 'thumbnail', 'revisions', 'custom-fields'),
Hopefully that helps.
You can add this code to your function.php. This code create new tab and add text field to this tab. Text field save to database like custom field in post_meta table and you can output this like default WP post meta.
1. Create tab Настройки UTM.
2. Create custom text field utm_post_class
3. To output in website use $utm = get_post_meta( $post->ID, 'utm_post_class', true );
//Article UTM Link
add_action( 'load-post.php', 'utm_post_meta_boxes_setup' );
add_action( 'load-post-new.php', 'utm_post_meta_boxes_setup' );
function utm_post_meta_boxes_setup() {
add_action( 'add_meta_boxes', 'utm_add_post_meta_boxes' );
add_action( 'save_post', 'utm_save_post_class_meta', 10, 2 );
}
function utm_add_post_meta_boxes() {
add_meta_box(
'utm-post-class',
'Настройки UTM',
'utm_post_class_meta_box',
'post',
'side',
'default'
);
}
function utm_post_class_meta_box( $post ) {
wp_nonce_field( basename( __FILE__ ), 'utm_post_class_nonce' );?>
<div class="components-base-control editor-post-excerpt__textarea">
<div class="components-base-control__field">
<label class="components-base-control__label" for="utm-post-class">UTM ссылка (необязательно)</label>
<input type="text" name="utm-post-class" id="utm-post-class" class="edit-post-post-schedule" value="<?php echo esc_attr( get_post_meta( $post->ID, 'utm_post_class', true ) ); ?>">
</div>
</div>
<?php }
function utm_save_post_class_meta( $post_id, $post ) {
if ( !isset( $_POST['utm_post_class_nonce'] ) || !wp_verify_nonce( $_POST['utm_post_class_nonce'], basename( __FILE__ ) ) )
return $post_id;
$post_type = get_post_type_object( $post->post_type );
if ( !current_user_can( $post_type->cap->edit_post, $post_id ) )
return $post_id;
$new_meta_value = ( isset( $_POST['utm-post-class'] ) ? $_POST['utm-post-class'] : '' );
$meta_key = 'utm_post_class';
$meta_value = get_post_meta( $post_id, $meta_key, true );
if ( $new_meta_value && '' == $meta_value )
add_post_meta( $post_id, $meta_key, $new_meta_value, true );
elseif ( $new_meta_value && $new_meta_value != $meta_value )
update_post_meta( $post_id, $meta_key, $new_meta_value );
elseif ( '' == $new_meta_value && $meta_value )
delete_post_meta( $post_id, $meta_key, $meta_value );
}
add_meta_box adds a new panel there for the gutenberg editor

custom gutenberg block - your site doesn't include support for the block

I want to create a block with editable fields, but I can't find out why I keep getting this error: 'Your site doesn't include support for the block. You can leave this block intact, convert its content to a Custom HTML block, or remove it entirely'. Does anyone know what might be producing such an error? Am I doing something wrong?
PHP code:
function protex_contact_gutenberg_block_enqueue_scripts(){
$required_js_files = array(
'wp-blocks',
'wp-i18n',
'wp-element',
'wp-editor'
);
wp_enqueue_script( 'react', 'https://unpkg.com/react#16/umd/react.development.js', $required_js_files );
$required_js_files[] = 'react';
wp_enqueue_script( 'react-dom', 'https://unpkg.com/react-dom#16/umd/react-dom.development.js', $required_js_files );
wp_enqueue_script( 'babel', 'https://unpkg.com/babel-standalone#6/babel.min.js', $required_js_files );
$required_js_files[] = 'babel';
wp_register_script( 'protex_contact_gutenberg_block_gutenberg_js', plugin_dir_url( __FILE__ ) . 'assets/prtx_contact.js', $required_js_files );
register_block_type('protex-contact/block', array(
'editor_script' => 'protex_contact_gutenberg_block_gutenberg_js',
'editor_script' => 'babel',
'editor_script' => 'react',
'editor_script' => 'react-dom',
));
}
add_action( 'init', 'protex_contact_gutenberg_block_enqueue_scripts' );
function protex_contact_gutenberg_block_gutenberg_modify_jsx_tag( $tag, $handle, $src ) {
if ( 'my_custom_gutenberg_block_gutenberg_js' == $handle ) {
$tag = str_replace( "<script type='text/javascript'", "<script type='text/babel'", $tag );
}
return $tag;
}
add_filter( 'script_loader_tag', 'protex_contact_gutenberg_block_gutenberg_modify_jsx_tag', 10, 3 );
JS code:
const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
const { RichText } = wp.editor;
registerBlockType( 'protex-contact/block', {
title: __( 'Protex konakt', 'protex-contact' ),
icon: 'id',
category: 'common',
attributes: {
content: {
type: 'string',
source: 'html',
selector: 'p',
},
},
edit({ attributes, className, setAttributes }) {
const { content } = attributes;
function onChangeContent( newContent ) {
setAttributes( { content: newContent } );
}
return (
<div className={ className }>
<RichText
tagName="p"
className="prtx_contact_input"
value={ content }
onChange={ onChangeContent } />
</div>
);
},
save({ attributes }) {
let { content } = attributes;
return (
<RichText.Content
tagName="p"
value={ content }
/>
);
},
} );
Check your path when registering this script:
wp_register_script( 'protex_contact_gutenberg_block_gutenberg_js', plugin_dir_url( __FILE__ ) . 'assets/prtx_contact.js', $required_js_files );
If you are calling plugin_dir_url( __FILE__ ) from a subdirectory, then the url will include that subdirectory. For example, if I call plugin_dir_url( __FILE__ ) from a file in the directory path 'plugins/my-custom-plugin/library', the url will end with '/my-custom-plugin/library/' which may not be the path you want.
If calling from a subdirectory, I would use
wp_register_script( 'protex_contact_gutenberg_block_gutenberg_js', plugins_url( 'assets/prtx_contact.js', dirname( __FILE__ ) ), $required_js_files );
If calling from many levels deep, then you may need to addjust dirname( __FILE__ ) to something like dirname( __FILE__ , 2 ) to traverse back up however far you need to go (or consider passing in the path to the "assets" folder so you don't have to calculate it on the fly).
I had a similar issue as you, and the problem was that the script was not being loaded due to an incorrect path. Outside of that, given the number of script dependencies you are registering, I would check that all the other scripts are being loaded correctly and not creating any issues.

How to add new panel under "document" in Gutenberg

I am trying to add a new component panel under document tab, like categories, featured image etc.
They've added the PluginDocumentSettingPanel SlotFill now.
const { registerPlugin } = wp.plugins
const { PluginDocumentSettingPanel } = wp.editPost
const PluginDocumentSettingPanelDemo = () => (
<PluginDocumentSettingPanel
name="custom-panel"
title="Custom Panel"
className="custom-panel"
>
Custom Panel Contents
</PluginDocumentSettingPanel>
)
registerPlugin('plugin-document-setting-panel-demo', {
render: PluginDocumentSettingPanelDemo
})
add_meta_box will do the trick, but only if you add the context-argument with a value of 'side':
add_meta_box(
'box-id-here',
'Box Title Here',
'createBoxHtml',
'post',
'side' ); // <-- this is important
Arrrh, two days for nothing!
Old answer
According to this tutorial, we can add our custom sidebar and fill it with customized form inputs.
Here is a working example in a React JSX version. This adds a meta field country:
const { registerPlugin } = wp.plugins;
const { PluginSidebar } = wp.editPost;
const { TextControl } = wp.components;
const { withSelect, withDispatch } = wp.data;
// Customized TextControl
const CustomMetaField = withDispatch( ( dispatch, props ) => {
return {
updateMetaValue: ( v ) => {
dispatch( 'core/editor' ).editPost( {
meta: {
[ props.metaFieldName ]: v
}
});
}
};
})( withSelect( ( select, props ) => {
return {
[ props.metaFieldName ]: select( 'core/editor' ).getEditedPostAttribute( 'meta' )[ props.metaFieldName ]
};
} )( ( props ) => (
<TextControl
value={props[ props.metaFieldName ] }
label="Country"
onChange={( v ) => {
props.updateMetaValue( v );
}}
/> )
) );
// Our custom sidebar
registerPlugin( 'custom-sidebar', {
render() {
return (
<PluginSidebar
name="project-meta-sidebar"
title="Project Meta">
<div className="plugin-sidebar-content">
<CustomMetaField metaFieldName="country" />
</div>
</PluginSidebar>
);
},
} );
And in PHP, register the meta field in the init-hook:
register_meta( 'post', 'country', [
'show_in_rest' => TRUE,
'single' => TRUE,
'type' => 'string'
] );
I know:
This is still not the required solution, but nearly.
You can now use the newer useSelect and useDispatch custom hooks. They are similar to withSelect and withDispatch, but utilize custom hooks from React 16.8 for a slightly more concise dev experience:
(Also, using #wordpress/scripts, so the imports are from the npm packages instead of the wp object directly, but either would work.)
import { __ } from '#wordpress/i18n';
import { useSelect, useDispatch } from '#wordpress/data';
import { PluginDocumentSettingPanel } from '#wordpress/edit-post';
import { TextControl } from '#wordpress/components';
const TextController = (props) => {
const meta = useSelect(
(select) =>
select('core/editor').getEditedPostAttribute('meta')['_myprefix_text_metafield']
);
const { editPost } = useDispatch('core/editor');
return (
<TextControl
label={__("Text Meta", "textdomain")}
value={meta}
onChange={(value) => editPost({ meta: { _myprefix_text_metafield: value } })}
/>
);
};
const PluginDocumentSettingPanelDemo = () => {
return (
<PluginDocumentSettingPanel
name="custom-panel"
title="Custom Panel"
className="custom-panel"
>
<TextController />
</PluginDocumentSettingPanel>
);
};
export default PluginDocumentSettingPanelDemo;
Along with registering your meta field as usual:
function myprefix_register_meta()
{
register_post_meta('post', '_myprefix_text_metafield', array(
'show_in_rest' => true,
'type' => 'string',
'single' => true,
'sanitize_callback' => 'sanitize_text_field',
'auth_callback' => function () {
return current_user_can('edit_posts');
}
));
}
add_action('init', 'myprefix_register_meta');
And make sure if using for a custom post type, that you include custom-fields in the array of supports:
'supports' => array('title', 'editor', 'thumbnail', 'revisions', 'custom-fields'),
Hopefully that helps.
You can add this code to your function.php. This code create new tab and add text field to this tab. Text field save to database like custom field in post_meta table and you can output this like default WP post meta.
1. Create tab Настройки UTM.
2. Create custom text field utm_post_class
3. To output in website use $utm = get_post_meta( $post->ID, 'utm_post_class', true );
//Article UTM Link
add_action( 'load-post.php', 'utm_post_meta_boxes_setup' );
add_action( 'load-post-new.php', 'utm_post_meta_boxes_setup' );
function utm_post_meta_boxes_setup() {
add_action( 'add_meta_boxes', 'utm_add_post_meta_boxes' );
add_action( 'save_post', 'utm_save_post_class_meta', 10, 2 );
}
function utm_add_post_meta_boxes() {
add_meta_box(
'utm-post-class',
'Настройки UTM',
'utm_post_class_meta_box',
'post',
'side',
'default'
);
}
function utm_post_class_meta_box( $post ) {
wp_nonce_field( basename( __FILE__ ), 'utm_post_class_nonce' );?>
<div class="components-base-control editor-post-excerpt__textarea">
<div class="components-base-control__field">
<label class="components-base-control__label" for="utm-post-class">UTM ссылка (необязательно)</label>
<input type="text" name="utm-post-class" id="utm-post-class" class="edit-post-post-schedule" value="<?php echo esc_attr( get_post_meta( $post->ID, 'utm_post_class', true ) ); ?>">
</div>
</div>
<?php }
function utm_save_post_class_meta( $post_id, $post ) {
if ( !isset( $_POST['utm_post_class_nonce'] ) || !wp_verify_nonce( $_POST['utm_post_class_nonce'], basename( __FILE__ ) ) )
return $post_id;
$post_type = get_post_type_object( $post->post_type );
if ( !current_user_can( $post_type->cap->edit_post, $post_id ) )
return $post_id;
$new_meta_value = ( isset( $_POST['utm-post-class'] ) ? $_POST['utm-post-class'] : '' );
$meta_key = 'utm_post_class';
$meta_value = get_post_meta( $post_id, $meta_key, true );
if ( $new_meta_value && '' == $meta_value )
add_post_meta( $post_id, $meta_key, $new_meta_value, true );
elseif ( $new_meta_value && $new_meta_value != $meta_value )
update_post_meta( $post_id, $meta_key, $new_meta_value );
elseif ( '' == $new_meta_value && $meta_value )
delete_post_meta( $post_id, $meta_key, $meta_value );
}
add_meta_box adds a new panel there for the gutenberg editor

Resources