WordPress is one of the most popular platforms for blogging and web content management in the world, allowing users to create and manage their own websites without needing programming knowledge. One of the attractive features of WordPress is the block editor, which allows for easy design of websites with the use of various blocks.
In this tutorial, we aim to teach the method of using the URL of WordPress pages within a custom block editor created in the WordPress block editor. This topic gives you the opportunity to add links to different pages on your own site and positively impact the user experience on your site.
Let's start by familiarizing ourselves with the concept known in the world of WordPress as "permalink." A permalink is essentially the URL of an individual page or post on the internet that is uniquely created for each piece of content. By using permalinks, you can create links that are attractive to users and can easily be discovered by search engines.
Next, we need to design a custom block in the WordPress block editor. For this, this block needs to link to an internal WordPress page, we need to be able to add the page URL to the block. For this task, different methods can be utilized, where here we will use JavaScript and React in the block editor.
In the next step, we will add functionality to the code and in the end, each line of code will be briefly and informally explained.
Custom Block Code with Page URL
<!-- Add to functions.php -->
wp.blocks.registerBlockType('my-custom/button', {
title: 'Button',
icon: 'button',
category: 'common',
edit: function(props) {
return (
<button
onClick={() => {
let link = prompt('Enter the page URL:');
if(link) {
window.location.href = link;
}
}}
>Click Me!</button>
);
},
save: function(props) {
return (
<button>Click Me!</button>
);
}
});
Line by Line Code Explanation:
wp.blocks.registerBlockType
: This function registers a new block in WordPress.title: 'Button'
: Specifies the block title that will be displayed in the editor.icon: 'button'
: The icon related to the block that will be displayed in the editor.category: 'common'
: Defines the category of the block which determines in which section of the editor it will be displayed.edit: function(props)
: A function that defines the edit functionality and the editable features of the block.return (<button>Click Me!</button>)
: Displays the block identified as a button and allows users to get the page URL upon clicking the button.save: function(props)
: A function that determines how the block data will be stored in the database and what will be displayed upon rendering.