I create the follow plugin to fullfill this: "Create wordpress plugin that does the following:
Has a button that shows up in the Gutenberg editor for a post, in the sidebar, often referred to as the "Document Sidebar" or "Settings Sidebar." This button will say “Generate title” When the generate title button is pressed, it will take the content of the post body and then take just the first 50 characters and set that as the title. Please make sure the plugin has any necessary configuration, etc so that it can be installed and activated in a similar manner to other wordpress plugins"
I use this code:
<?php
/**
* Plugin Name: Generate Title
* Plugin URI: https://github.com/546546
* Description: A WordPress plugin that generates the post title based on the first 50 characters of the post content.
* Version: 1.0
* Requires at least: 5.2
* Requires PHP: 7.2
* Author: My Name
* Author URI: my website
* License: GPL v2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/
// Add custom JavaScript logic for the Generate Title button
// Add button to Gutenberg editor sidebar
function add_generate_title_button() {
if ( ! function_exists( 'register_block_type' ) ) {
// Gutenberg not active
return;
}
register_block_type( 'generate-title/button', array(
'render_callback' => 'render_generate_title_button'
));
}
add_action( 'init', 'add_generate_title_button' );
// Render button HTML
function render_generate_title_button() {
?>
<button onclick="generateTitle()">Generate Title</button>
<?php
}
// JS to hook click and generate title
function add_generate_title_script() {
?>
<script>
function generateTitle() {
const content = document.querySelector('.editor-post-text-editor__content');
const title = document.querySelector('.editor-post-title__input');
if (content.innerHTML && title) {
title.value = content.innerHTML.substr(0,50);
}
}
</script>
<?php
}
add_action( 'admin_footer', 'add_generate_title_script' );
?>
I'm new on Wordpress, this doesn't show any button on my Guttenberg, and I don't know why, I have the last version of Wordpress and I have no errors on the Browser console. Is not a cache thing.