Exploring WordPress APIs
Introduction
In this section, we will step away from Gutenberg block development to explore the various APIs available in WordPress. These APIs provide a range of functions, allowing developers to interact with the WordPress system more effectively.
What is an API?
An API (Application Programming Interface) is a set of functions, variables, and classes that a system provides for developers to interact with. In our case, WordPress serves as the system, and we’ve already been utilizing its APIs in our theme and plugin development.
Overview of Key APIs
1. Dashboard Widgets API
- Purpose: Add widgets to the WordPress admin dashboard.
- Usage: Helps enhance the admin experience by providing custom information.
2. Database API
- Purpose: Functions for interacting with the WordPress database.
- Focus: We will delve into additional functions related to this API later in this section.
3. File Header API
- Purpose: Read metadata from files, useful for creating plugin systems or reading data from other plugins.
- Note: Not commonly used, but it’s good to know it’s available.
4. File System API
- Purpose: Transfer files securely between servers, used by WordPress for updates.
- Usage: Not typically utilized in standard plugin development.
5. HTTP API
- Purpose: Send HTTP requests using PHP.
- Benefits: Simplifies the process of sending requests, allowing you to handle complex operations with ease.
6. Metadata API
- Purpose: Handle metadata associated with WordPress entities.
- Note: We will skip an in-depth discussion as we’ve covered this previously.
7. Options API
- Purpose: Manage options stored in the database.
- Focus: We will explore this API further in the next lectures.
8. Plugin API
- Purpose: Add action hooks and filter hooks, essential for extending WordPress functionality.
- Familiarity: This is one of the most commonly used APIs in WordPress development.
9. Quick Tags API
- Purpose: Add buttons to the classic editor.
- Note: Outdated due to Gutenberg’s introduction.
10. Rewrite API
- Purpose: Access and manipulate URL structures in WordPress.
- Focus: Discussed during plugin activation.
11. Settings API
- Purpose: Manage settings for your plugin or theme.
- Focus: We’ll cover this in detail later.
12. Shortcodes API
- Purpose: Create custom content before the introduction of blocks.
- Note: Outdated and not covered in this course.
13. Customization APIs
- Purpose: Originally used for modifying theme appearance through the WordPress customizer.
- Note: Phased out in favor of full site editing.
14. Transients API
- Purpose: Temporarily cache data in the database.
- Note: Briefly covered during block development.
15. Widgets API
- Purpose: Add content to theme sidebars.
- Note: Being phased out with the rise of block development.
16. XML-RPC API
- Purpose: Enable mobile and desktop apps to connect to a WordPress site.
- Note: Not covered in this course as it focuses on mobile app development.
Understanding the Options API
Introduction
We’ll explore the Options API, a powerful tool for managing settings within WordPress. This API enables developers to store and manipulate data that affects various aspects of WordPress, not just page content.
What is the Options API?
The Options API provides a standardized method for storing data in the WordPress database. This is particularly useful for adding settings related to plugins or themes. Instead of creating separate tables for each plugin’s settings—which can clutter the database—WordPress allows us to utilize the wp_options
table.
Key Features
- Simple Data Management: The API simplifies the process of creating, accessing, updating, and deleting options stored in the database.
- Centralized Storage: All data is stored in the
wp_options
table, which has a straightforward structure:- Option Name: A unique identifier for the setting.
- Option Value: The value associated with the setting.
Benefits
- Reduced Clutter: By standardizing how settings are stored, WordPress keeps the database organized, avoiding the complications of multiple tables.
- Ease of Use: Developers can interact with the options table using WordPress functions instead of writing custom SQL queries.
Database Overview
The wp_options
table contains various settings for both WordPress and any installed plugins. The table’s structure is simple:
- Each row represents a single setting, with columns for the option name and its corresponding value.
- It’s possible to store multiple values in a single record, although best practices typically encourage keeping it simple.
Adding Settings with the Options API
Introduction
W e’ll learn how to create settings for our plugin using the Options API. We’ll focus on initializing these settings during plugin activation to ensure a smooth setup process.
Creating Plugin Settings
We’ll start by adding options to the database when the plugin is activated. This is a great way to ensure that all necessary settings are in place without cluttering the database with unnecessary data.
Step-by-Step Process
- Open the Activation File: Start by accessing the activation file for your plugin.
- Retrieve Existing Options:
- Create a variable called
options
using theget_option()
function to check if the settings already exist. - Use a unique name for the option, prefixed to avoid naming conflicts (e.g.,
up_options
).
$options = get_option('up_options');
- Create a variable called
- Check for Existing Data:
- Use a conditional statement to check if
$options
is false. If it is, we can proceed to add our settings.
if ($options === false) { // Proceed to add options }
- Use a conditional statement to check if
- Add Options:
- Use the
add_option()
function to create a new entry in thewp_options
table. - Pass the name and value for the option. We’ll store Open Graph settings in an array, which can include:
OG title
: Retrieved fromget_bloginfo('name')
.OG image
: Start with an empty string.OG description
: Retrieved fromget_bloginfo('description')
.enable OG
: Default to1
(enabled).
add_option('up_options', [ 'OG_title' => get_bloginfo('name'), 'OG_image' => '', 'OG_description' => get_bloginfo('description'), 'enable_OG' => 1, ]);
- Use the
Understanding Open Graph
Open Graph is a protocol that allows web pages to become rich objects in social media. When a link is shared on platforms like Facebook, the Open Graph data specifies what image, title, and description to display.
- Benefits: By enabling users to modify Open Graph settings, you help them manage how their content is presented on social media, enhancing engagement.
Testing the Implementation
To verify that our options were added correctly:
- Navigate to the Plugins Page: Deactivate and then reactivate your plugin.
- Check the Database: Look at the
wp_options
table. Your new settings should appear as a serialized array.
Note on Serialization
WordPress automatically serializes arrays before inserting them into the database. This means that when we store our options, they are transformed into a format that can be easily retrieved later.
Creating a Custom Admin Page for Plugin Options
Introduction
We will create a custom admin page for displaying and managing the options of our plugin. This involves using the add_menu_page
function and setting up the necessary hooks and functions.
Step-by-Step Guide
1. Hook into Admin Menu
To add our custom admin page, we need to hook into the WordPress admin menu. Open the index.php
file of your plugin and add the following:
phpCopy codeadd_action('admin_menu', 'up_admin_menus');
2. Define the Function
Next, we’ll define the up_admin_menus
function in a new file called menus.php
located in the includes/admin
folder. This function will call add_menu_page
.
phpCopy codefunction up_admin_menus() {
add_menu_page(
__('Udemy Plus', 'textdomain'), // Page title
__('Udemy Plus', 'textdomain'), // Menu title
'edit_theme_options', // Capability
'up_plugin_options', // Menu slug
'up_plugin_options_page', // Function to render the page
plugins_url('letter_u.svg', __FILE__), // Icon URL
100 // Position
);
}
3. Creating the Options Page Function
Now, create a new file called options-page.php
in the includes/admin
folder. Inside this file, define the up_plugin_options_page
function to render the content of the admin page.
phpCopy codefunction up_plugin_options_page() {
echo '<div class="wrap">';
echo '<h1>' . __('Udemy Plus Options', 'textdomain') . '</h1>';
echo '<p>' . __('Manage your plugin settings here.', 'textdomain') . '</p>';
echo '</div>';
}
4. Adding an Icon
To give our menu item an icon, we can use a custom SVG. Download the SVG file and place it in the root directory of your plugin, naming it letter_u.svg
.
5. Update the Icon Path
Make sure the add_menu_page
function uses the correct path for the icon. You can do this with the plugins_url
function, as shown above.
6. Finalizing the Setup
Ensure that you have included the necessary files in your main plugin file (e.g., index.php
). Here’s how you can include menus.php
and options-page.php
:
phpCopy coderequire_once plugin_dir_path(__FILE__) . 'includes/admin/menus.php';
require_once plugin_dir_path(__FILE__) . 'includes/admin/options-page.php';
7. Testing in the Browser
Refresh the WordPress admin dashboard. You should see a new menu item labeled “Udemy Plus”. Clicking on it will take you to the options page where your welcome message is displayed.
Updating the Custom Admin Page with a Form
Introduction
We will enhance our custom admin page by adding a form that allows users to modify plugin settings. This form will include fields for Open Graph settings, including title, image, description, and an option to enable or disable Open Graph tags.
Step-by-Step Guide
1. Decide on Form Design
We’ll use WordPress’s built-in classes for the form to maintain a consistent user experience. To aid in the design process, consider using the WordPress Admin Styles plugin to see available classes.
2. Prepare the Form Structure
Here’s a basic outline of the form structure. We’ll add this inside the <div class="wrap">
in the options-page.php
file.
phpCopy code<form method="post" action="admin-post.php">
<input type="hidden" name="action" value="up_save_options">
<?php wp_nonce_field('up_options_verify'); ?>
<table class="form-table">
<tr>
<th scope="row"><label for="og_title"><?php esc_html_e('Open Graph Title', 'textdomain'); ?></label></th>
<td><input name="og_title" type="text" id="og_title" value="<?php echo esc_attr($options['og_title']); ?>" class="regular-text"></td>
</tr>
<tr>
<th scope="row"><label for="og_image"><?php esc_html_e('Open Graph Image', 'textdomain'); ?></label></th>
<td><input name="og_image" type="text" id="og_image" value="<?php echo esc_attr($options['og_image']); ?>" class="regular-text">
<img src="<?php echo esc_url($options['og_image']); ?>" alt="" style="max-width: 100px; display: block; margin-top: 5px;"></td>
</tr>
<tr>
<th scope="row"><label for="og_description"><?php esc_html_e('Open Graph Description', 'textdomain'); ?></label></th>
<td><textarea name="og_description" id="og_description" rows="5" class="large-text"><?php echo esc_html($options['og_description']); ?></textarea></td>
</tr>
<tr>
<th scope="row"><?php esc_html_e('Enable Open Graph', 'textdomain'); ?></th>
<td><input name="enable_og" type="checkbox" id="enable_og" value="1" <?php checked(1, $options['enable_og']); ?> /></td>
</tr>
</table>
<?php submit_button(); ?>
</form>
3. Add Nonce for Security
We include a nonce field for security purposes. This helps validate that the form submission came from the actual site. The wp_nonce_field
function takes care of this.
4. Update Input Values
For each input field, we will pre-fill them with existing values from our options. We use functions like esc_attr()
and esc_html()
to ensure the output is safe.
5. Submit Button
The submit_button()
function generates a styled submit button for the form.
6. Test the Form
After you’ve implemented the form, refresh your custom admin page. You should see the form with pre-filled values based on your stored options.
7. Inspect the Form
Inspect the form to confirm that:
- The inputs for the title, image, and description are correctly populated.
- The checkbox for enabling Open Graph is checked by default if enabled.
Handling Form Submission
Introduction
We will learn how to handle the form submission from our custom admin page in WordPress. We’ll capture the submitted data and prepare to update our plugin settings.
Step-by-Step Guide
1. Define the Submission Handler
We will create a function to process the form data when the form is submitted. This function will be hooked into WordPress’s admin_post
action.
Adding the Hook
Open your main plugin file and add the following code at the bottom of the hook section:
phpCopy codeadd_action('admin_post_up_save_options', 'up_save_options');
This hook listens for the up_save_options
action, which corresponds to the value set in the action
attribute of our form.
2. Create the Function
Next, create a new file named save-options.php
in the includes/admin
folder. Inside this file, define the up_save_options
function:
phpCopy codefunction up_save_options() {
// Output the contents of the $_POST variable for debugging
print_r($_POST);
exit; // Stop further execution for testing
}
3. Understanding the $_POST
Variable
When the form is submitted, the data from the input fields will be available in the $_POST
superglobal array. This array holds all data sent via the POST method.
4. Testing the Submission
Now, go back to your browser and submit the form without changing any values. If everything is set up correctly, you should see the output of the $_POST
array on the screen, showing all the submitted data.
Updating Plugin Settings and Securing Form Submission
We will secure our form submission process, validate user permissions, and update our plugin settings with the submitted data. We’ll ensure that our form is secure against unauthorized access and process the input data appropriately.
Step-by-Step Guide
1. Securing the Form Submission
Validate User Permissions
At the top of the up_save_options
function in save-options.php
, we will check if the current user has the capability to edit theme options:
phpCopy codeif (!current_user_can('edit_theme_options')) {
wp_die(__('You are not allowed to be on this page.'));
}
This code checks the user’s capabilities. If the user doesn’t have permission, it stops the script and shows a message.
Validate the Nonce
Next, we will verify the nonce to protect against CSRF attacks:
phpCopy codecheck_admin_referer('up_options_verify');
This function will verify that the nonce sent with the form is valid. If not, the script will stop executing.
2. Updating Plugin Options
Now, we will proceed to update the plugin settings based on the submitted form data.
Retrieve Existing Options
First, retrieve the existing options from the database:
phpCopy code$options = get_option('up_options');
Sanitize and Update Inputs
Next, we will update the options with sanitized values:
phpCopy code$options['og_title'] = sanitize_text_field($_POST['up_og_title']);
$options['og_image'] = esc_url_raw($_POST['up_og_image']);
$options['og_description'] = sanitize_textarea_field($_POST['up_og_description']);
$options['enable_og'] = isset($_POST['up_enable_og']) ? 1 : 0;
This code sanitizes the input to prevent any harmful data from being saved in the database.
Update Options in the Database
To save the updated options, use:
phpCopy codeupdate_option('up_options', $options);
3. Redirecting the User
After updating the options, we will redirect the user back to the options page with a success message:
phpCopy codewp_redirect(admin_url('admin.php?page=up_plugin_options&status=1'));
exit;
4. Displaying Success Messages
In the options-page.php
file, we will add code to display a success message if the status
parameter is set:
phpCopy codeif (isset($_GET['status']) && $_GET['status'] == 1) {
echo '<div class="notice notice-success is-dismissible">
<p>' . esc_html__('Options updated successfully.', 'your-text-domain') . '</p>
</div>';
}
5. Testing the Form
With the above code in place, refresh your custom admin page and submit the form. If everything is set up correctly, you should see a success message indicating that the options have been updated.
Integrating the Media Library for Image Selection
We’ll add a media library popup to our custom admin page, allowing users to select images directly from the WordPress media library. This feature enhances user experience and makes it easier to manage media files.
Step-by-Step Guide
1. Enqueue the Media Library Scripts
Register the Hook
First, we need to enqueue the necessary scripts for the media library. Open the main plugin file (index.php
) and add an action hook to enqueue scripts in the admin dashboard:
phpCopy codeadd_action('admin_enqueue_scripts', 'up_admin_enqueue_scripts');
Define the Function
Next, create a new file in the includes/admin
directory called enqueue.php
and define the up_admin_enqueue_scripts
function:
phpCopy codefunction up_admin_enqueue_scripts($hook_suffix) {
// Check if we are on our custom admin page
if ($hook_suffix !== 'toplevel_page_up_plugin_options') {
return;
}
// Enqueue the media library scripts
wp_enqueue_media();
}
2. Inspecting the Hook Suffix
To ensure our function only runs on the custom admin page, we need to verify the hook suffix. Add this line temporarily to your function to inspect the value:
phpCopy codeecho '<script>console.log("' . $hook_suffix . '");</script>';
Then refresh the custom admin page. Open the console in your browser’s developer tools to see the output. Once you have confirmed the value, remove the console log line.
3. Adding the Button to Open the Media Library
In the options-page.php
file, we’ll add a button that users can click to open the media library. Here’s how to do it:
- Find the input field where users will set the Open Graph image.
- Below that input, add a button with a class to trigger the media library:
phpCopy code<button type="button" class="button" id="upload_image_button">Upload Image</button>
4. JavaScript for Opening the Media Library
Now we need to write some JavaScript to handle the button click and open the media library. We can add this inline in our options page:
phpCopy code<script>
jQuery(document).ready(function($){
var mediaUploader;
$('#upload_image_button').click(function(e) {
e.preventDefault();
// If the uploader object has already been created, reopen the dialog
if (mediaUploader) {
mediaUploader.open();
return;
}
// Extend the wp.media object
mediaUploader = wp.media({
title: 'Select Image',
button: {
text: 'Use this image'
},
multiple: false // Set to true to allow multiple files to be selected
});
// When a file is selected, grab the URL and set it as the input's value
mediaUploader.on('select', function() {
var attachment = mediaUploader.state().get('selection').first().toJSON();
$('#up_og_image').val(attachment.url); // Assuming 'up_og_image' is the ID of your input field
});
// Open the uploader dialog
mediaUploader.open();
});
});
</script>
5. Testing the Media Library Integration
With the above code in place:
- Refresh your custom admin page.
- Click the “Upload Image” button.
- Select an image from the media library and ensure that the image URL populates in the corresponding input field.
Modifying Webpack Configuration for Custom Files
In this lecture, we’ll modify the Webpack configuration to include custom JavaScript files for our admin dashboard. By default, WordPress’s Webpack setup focuses primarily on blocks, but we can extend it to bundle additional files.
Step-by-Step Guide
1. Create the Admin JavaScript File
First, we’ll create a directory and a JavaScript file for our admin-specific scripts.
- Create a Folder: In the
source
directory, create a new folder namedadmin
. - Create the File: Inside the
admin
folder, create a file calledindex.js
.
Add a simple log statement to verify that the file is being included correctly:
javascriptCopy codeconsole.log('Admin scripts loaded');
2. Set Up the Webpack Configuration
Next, we need to create a Webpack configuration file in the root of the plugin.
- Create the Webpack Config File: In the root directory, create a file called
webpack.config.js
.
3. Import the Default WordPress Configuration
To build on the existing WordPress configuration, we’ll need to import it. At the top of your webpack.config.js
, add the following code:
javascriptCopy codeimport defaultConfig from '@wordpress/scripts/config/webpack.config.js';
4. Enable Module Support
To use ES module imports in Node.js, update your package.json
file. Add the following line:
jsonCopy code"type": "module"
This change allows Node.js to recognize your files as ES modules, enabling the use of import
statements.
5. Create Your Webpack Configuration
In webpack.config.js
, we will merge the default WordPress configuration with our own. Start by exporting an object:
javascriptCopy codeconst { merge } = require('webpack-merge');
export default merge(defaultConfig, {
// Custom configuration will go here
});
6. Set the Entry Point
We need to specify our custom admin file as an entry point while still preserving WordPress’s existing entry points. Here’s how to do it:
javascriptCopy codeexport default merge(defaultConfig, {
entry: {
// Spread the default entry points
...defaultConfig.entry,
// Add your admin script
'admin/index': './source/admin/index.js',
},
});
7. Testing the Configuration
Now that we have updated the Webpack configuration:
- Start Webpack: If you already have the start command running, restart it. In the command line, run:bashCopy code
npm start
- Check the Build Directory: Navigate to the
build
directory in your plugin. You should see a new folder calledadmin
, containing the bundled JavaScript file.
8. Verify the Bundle
Open the bundled file to ensure that it includes your custom admin script and that there are no errors. The presence of the console log message will confirm that your script is being executed.
Loading Files for the Admin Dashboard
In this lecture, we’ll learn how to load custom styles and scripts for our admin dashboard, ensuring that our media library integrates smoothly with the overall design.
Step-by-Step Guide
1. Create a CSS File for Styles
First, we need to create a CSS file to style our admin page.
- Create a CSS File: In the
source/admin
directory, create a file calledmain.css
.
Add the following styles to constrain the size of the image preview:
cssCopy code#og-image-preview {
display: block;
margin-bottom: 20px;
max-width: 600px;
}
2. Import the CSS File in Your JavaScript
Next, we’ll import this CSS file into our main JavaScript file.
- Open
index.js
: At the top of yourindex.js
file, add the import statement:
javascriptCopy codeimport './main.css';
3. Check the Build Directory
After saving your changes, ensure that the build process has generated the CSS file.
- Check the
build/admin
Directory: Look formain.css
. If it’s not there, restart the Webpack command.
4. Register and Enqueue the Files
Now, we will register and enqueue the CSS and JavaScript files so that they load only on the relevant admin page.
- Open the Main Plugin File: Go to your main plugin file and scroll to the bottom.
- Add the Init Hook: Add the following code to set up an
init
hook:
phpCopy codeadd_action('init', 'up_register_assets');
5. Create the Register Assets Function
Create a new PHP file in the includes
directory called register-assets.php
. Inside this file, define the up_register_assets
function.
phpCopy codefunction up_register_assets() {
// Register CSS
wp_register_style('up-admin', plugin_dir_url(__FILE__) . 'build/admin/main.css', array(), null);
// Register JavaScript
wp_register_script('up-admin', plugin_dir_url(__FILE__) . 'build/admin/index.js', array(), null, true);
}
6. Include the PHP File
Make sure to include the register-assets.php
file in your main plugin file:
phpCopy coderequire_once plugin_dir_path(__FILE__) . 'includes/register-assets.php';
7. Enqueue the Assets Conditionally
Open your enqueue.php
file and conditionally load the scripts and styles only on your custom admin page.
phpCopy codeif (isset($_GET['page']) && $_GET['page'] === 'your_custom_page_slug') {
wp_enqueue_style('up-admin');
wp_enqueue_script('up-admin');
}
8. Test the Changes
Refresh your admin page. Ensure that:
- The image displays correctly with the applied styles.
- The JavaScript functionality is working as expected.
Additional Notes on Generated Files
In the build/admin
directory, you may notice additional files generated by Webpack:
- Source Maps: These files help debug minified code by mapping it back to the original source.
- Assets PHP File: This file contains an array of dependencies and versioning information, helping manage the script registration.
You can include this file to access its contents for more precise asset management.
9. Including the Assets PHP File
To utilize the dependencies from the assets file, modify your register-assets.php
like this:
phpCopy code$admin_assets = include plugin_dir_path(__FILE__) . 'build/admin/index.assets.php';
wp_register_script('up-admin', plugin_dir_url(__FILE__) . 'build/admin/index.js', $admin_
Creating a Custom Image Size for Open Graph
We’ll create a custom image size specifically for Open Graph images, which should have dimensions of 1200 by 630 pixels. Here’s how to do it step-by-step.
Step 1: Register the Custom Image Size
- Open the
setup.php
File: This is where you’ll define the new image size. - Add the Custom Image Size: Use the
add_image_size
function to register the new size. Add the following code:phpCopy codeadd_image_size('open-graph', 1200, 630, true);
- Parameters:
'open-graph'
: This is the name of the image size.1200
: The width in pixels.630
: The height in pixels.true
: This parameter enables cropping to exact dimensions.
- Parameters:
Step 2: Expose the Image Size via REST API
- Open the
image-sizes.php
File: This file should contain the filter for exposing image sizes in the REST API. - Add the Open Graph Size: Modify the filter to include your new image size:phpCopy code
add_filter('rest_prepare_attachment', function ($response, $attachment) { $response->data['media_details']['sizes']['open-graph'] = [ 'width' => 1200, 'height' => 630, 'file' => $attachment->get_file(), 'mime_type' => $attachment->get_mime_type(), ]; return $response; }, 10, 2);
Step 3: Regenerate Thumbnails
Since the new image size will only apply to images uploaded after registering the size, you need to regenerate existing images:
- Navigate to the Admin Dashboard: Find the “Regenerate Thumbnails” tool, often found under “Tools” or via a dedicated plugin.
- Start the Regeneration Process: Follow the prompts to regenerate all images. This will ensure that images already uploaded to the media library will now include the new Open Graph size
Implementing the Media Library Button
In this lecture, we’ll set up a button that allows users to open the WordPress media library and select an image. After an image is selected, it will be displayed as a preview, and the image URL will be stored for form submission. Let’s dive into the implementation.
Step-by-Step Implementation
- Open the
index.js
File: This is where we will add the JavaScript code to handle the media library. - Select the Elements:
- Create variables to reference the button, image preview, and input field:
const ogImageButton = document.querySelector('#og-image-button'); const ogImageContainer = document.querySelector('#og-image-preview'); const ogImageInput = document.querySelector('#og-image');
- Initialize the Media Library:
- Create a variable for the media frame and set it using
wp.media()
:
const mediaFrame = wp.media({ title: 'Select or Upload Media', button: { text: 'Use this media' }, multiple: false // Prevent multiple selections });
- Create a variable for the media frame and set it using
- Open the Media Library on Button Click:
- Add an event listener to the button:
ogImageButton.addEventListener('click', (event) => { event.preventDefault(); // Prevent the default anchor behavior mediaFrame.open(); // Open the media library });
- Handle Image Selection:
- Use the
on
method to listen for theselect
event:
mediaFrame.on('select', () => { const attachment = mediaFrame.state().get('selection').first().toJSON(); ogImageContainer.src = attachment.sizes.open-graph.url; // Update the preview ogImageInput.value = attachment.sizes.open-graph.url; // Store the URL });
- Use the
Explanation of the Code
- Element Selection: We’re using
document.querySelector()
to grab elements by their IDs. This makes it easy to manipulate them later. - Media Frame Initialization: The
wp.media()
function initializes the media library with options for title, button text, and selection limits. - Event Listener for Button Click: The click event prevents the default behavior (which could redirect the user) and opens the media library when the button is clicked.
- Handling Image Selection: The
select
event is triggered when the user selects an image. We retrieve the selected image, update the preview image source, and set the input field value with the image URL.
Testing the Implementation
- After implementing the above code, refresh your admin page and click the button to open the media library.
- Select an image, and ensure it appears in the preview area.
- The URL of the selected image should be stored in the hidden input field.
Recreating the Form with the Settings API
In this lecture, we’ll use the WordPress Settings API to recreate our form. While the Settings API can be a bit cumbersome, it provides benefits like consistency, security, and reduced development time. Let’s get started!
Steps to Implement the Settings API
- Create a Submenu Page:
- Open the
menu.php
file in your plugin. - Use the
add_submenu_page()
function to add a submenu under your main plugin menu:
add_submenu_page( 'udemy-plus', // Parent menu slug __('Udemy Plus Options', 'textdomain'), // Page title __('Udemy Plus', 'textdomain'), // Menu title 'edit_theme_options', // Capability 'udemy-plus-options', // Menu slug 'udemy_plus_options_page' // Function to display the page );
- Open the
- Define the Options Page Function:
- Create a new file in the
includes/admin
directory calledoptions-page-alt.php
. - Define the function that renders the options page:
function udemy_plus_options_page() { ?> <div class="wrap"> <h1><?php _e('Udemy Plus Options', 'textdomain'); ?></h1> <form method="post" action="options.php"> <?php settings_fields('udemy_plus_options_group'); // Register settings group do_settings_sections('udemy-plus'); // Render settings sections submit_button(); // Add the submit button ?> </form> </div> <?php }
- Create a new file in the
- Register Settings:
- In your main plugin file or a dedicated file, register your settings using
register_setting()
andadd_settings_section()
:
function udemy_plus_register_settings() { register_setting('udemy_plus_options_group', 'udemy_plus_image_url'); // Register a setting add_settings_section( 'udemy_plus_main_section', __('Main Settings', 'textdomain'), 'udemy_plus_section_text', 'udemy-plus' // Use the same slug as above ); add_settings_field( 'udemy_plus_image_field', // ID __('Open Graph Image URL', 'textdomain'), // Title 'udemy_plus_image_field_render', // Callback 'udemy-plus', // Page slug 'udemy_plus_main_section' // Section ID ); } add_action('admin_init', 'udemy_plus_register_settings');
- In your main plugin file or a dedicated file, register your settings using
- Create the Callback Functions:
- Define the callback functions for the settings section and the input field:
function udemy_plus_section_text() { echo '<p>' . __('Enter your settings below:', 'textdomain') . '</p>'; } function udemy_plus_image_field_render() { $image_url = get_option('udemy_plus_image_url', ''); echo '<input type="text" name="udemy_plus_image_url" value="' . esc_attr($image_url) . '" />'; }
- Testing the Options Page:
- Refresh your WordPress admin dashboard.
- Click on the “Udemy Plus” submenu to see your options page.
- You should see the input field for the Open Graph Image URL, along with a submit button.
Explanation of the Code
- Submenu Registration: The
add_submenu_page()
function creates a submenu item under your main plugin menu. It links to a function that renders the options page. - Options Page Rendering: The
options.php
action allows WordPress to handle saving settings automatically. Thesettings_fields()
function adds necessary hidden fields for security. - Settings Registration:
register_setting()
associates a setting with a specific options group. Theadd_settings_section()
andadd_settings_field()
functions define where to place your settings in the form. - Callback Functions: These functions display the text for the section and the input field for the image URL.
Registering Options with a Group
Introduction
Will register our option with a group.
Understanding WordPress Pages
To understand why, let’s look at the pages created by WordPress.
General Settings Page
For example, I’m viewing the page for the general settings.
Fields and Database Records
On this page we have multiple fields. Each field can modify a specific record from the database.
WP Options Table
If you were to look through the WP options table, most of the records contain a single value.
Grouping Options
WordPress does not know how to group options for a single page. We must teach WordPress what group of options it can modify from a page. This is known as an options group.
Technical Overview
Technically, we have a single record containing our plugins options. They’re spread across multiple records.
Initial Steps
Regardless, the first step for using the Settings API is to register our option with a group.
Getting Started
Let’s get started in your editor. Open the indexed PHP file.
Adding Action Hook
At the bottom of the file, add an action hook called admin in it. WordPress has a hook during the initialization step of the admin dashboard. We must register our option group during this hook.
Defining the Function
The name of our function will be called up settings API. Next, let’s define this function inside the include slash admin folder.
Creating Settings API File
Create a file called Settings API php. Inside this file, define the up settings API function.
Registering Setting
Afterward, run a function called register setting. This function will register an option with a group.
Arguments for Registering
The first argument is the name of the group. The name of our group can be anything we want. Let’s set the name to Up Options Group.
Registering an Option
Next, we must register a single option with this group by passing in the options name as the second argument. The name of our option was called up options.
Multiple Options Example
If you have multiple options, this function must be called for each option. For example, let’s say we had an option called B, we would call this function like so.
Second Invocation
The second invocation of this function would belong to the same group. However, the second argument would register the second option. In our case, we only have one option. So calling this function once is more than enough.
Rendering the Group
After registering our option with a group, we can render this group in our form open the options page.
Modifying the Options Page
Open the options page. PHP file. Inside the div tag, add a form tag. On this tag set the method attribute to post. Next set the action attribute to options, not PHP.
Key Differences
Here’s a huge difference between the Settings API and manually creating a form for modifying options. Forms created with the Settings API must send data to the options PHP file. This file is dedicated to handling form submissions for the settings API.
Manual Form Handling
If we’re creating a form without this API, the data must be sent to the admin post’s PHP file.
Implementing Settings Fields
Inside this form, let’s run a function called settings fields. This function will tell the options PHP file which option group will be modified by this form?
Argument for Settings Fields
This function has one argument which is the name of the options group. Let’s pass in the name of our group. This step is very important. Otherwise, WordPress will not know what options group to modify.
Adding a Section to the Form
Introduction
In this lecture, we are going to add a section to our form.
Importance of Organizing Input Fields
Adding dozens of input fields on a page can feel overwhelming to a user. We can group inputs into sections for readability.
Example of Sections
For example, I am viewing the permalink page in the admin dashboard. This page has two sections. They’re called Common Settings and Optional. Each section has a different set of inputs.
Purpose of Sections
The purpose of a section is to organize fields into groups. All fields must belong to a section. At the moment we have a single option. Therefore we are going to have a single field.
Requirement for Sections
Regardless, this field must belong to a section before creating the field. A section must be created for containing the options field.
Getting Started
Let’s get started by opening the settings API PHP file.
Registering the Section
Inside the function, run a function called ad settings section. This function will register a section with our form.
Arguments for Adding a Section
It has four arguments.
First Argument: Section ID
The first argument is the ID of the section. A page can have multiple sections. WordPress needs to be able to identify them. The ID can be anything. Let’s set the ID to up options section.
Second Argument: Section Title
Next, we must provide the title of the section. Let’s set this argument to the following translatable message: Udemy plus settings.
Third Argument: Rendering Function
The third argument is the function for rendering this section’s content. Normally, developers will render additional text to help users fill out the form. It’s completely optional to add additional text.
Example Rendering Function
For demonstration purposes, let’s add a function called Up Options Section CB. Let’s define this function below. Normally we would create a separate file for a function. However, these functions belong to the page. Therefore, I don’t mind using the same file.
Outputting Content
Let’s output a paragraph tag with the following message: an alternative form for updating options with the settings API.
Assigning the Section to a Page
Let’s head back to the ad settings section function. The last argument is to assign this section to a page. Currently, WordPress does not know where to render this section. Let’s call our page up options page.
Rendering the Section
After defining the section, we must render this section from within our page. Open the options page. PHP file. Below these settings fields, run a function called do settings sections. This function will begin rendering sections for a specific page.
Argument for Rendering Sections
It has one argument, which is the name of the page. This argument corresponds to the fourth argument in the ad settings section function. Let’s pass in up options page.
Adding a Submit Button
Before testing our code, let’s run the submit button function to add a button for submitting the form.
Testing the Code
All right, let’s refresh our page. The section has been successfully rendered. The section renders a title and paragraph below our section. We have a button for submitting the form.
Adding Fields to the Form
Introduction
We are going to begin adding fields to our form. This step is very easy.
Importance of Adding Fields
Similar to other steps, WordPress has a function for adding a field. Fields must be added to a section. Luckily we have a section on our page. Our fields can be added to this section.
Getting Started
Let’s get started by opening the settings API PHP file.
Adding a Field
At the bottom of the function, run a function called add settings fields. This function will add a field to a section. There are five arguments.
First Argument: Field ID
The first argument is an ID for the field. Let’s set the ID to ogg title input.
Second Argument: Field Label
Next, we must add the text for the label. The label will sit to the side of the input. This input will represent the title of the open graph. Let’s use the following translatable text: open graph title.
Third Argument: Rendering Function
Up next, we must provide a function for rendering the input. The input element is our responsibility. The Settings API does not render this element, but it will help us with setting the value. The name of our function will be called OGG Title Input CB. In a moment, we will define this function.
Fourth Argument: Page Name
Let’s move on to the next argument, which is the page’s name. WordPress doesn’t know which page the input will appear on. Therefore, we must provide the name. The value must correspond with the value passed into the do settings section’s function. In our case, the page’s name is called Up Options Page.
Fifth Argument: Section Name
Lastly, we must provide the name of the section. Our section is called Up Options Section.
Defining the Rendering Function
Great. The last step is to define the function for rendering the input below this function. Define the OGG Title Input CB function.
Outputting the Input Element
In this function, we can output an input element for storing the value. First, let’s grab the option. Define a variable called options. The value for this variable will be the get option function. The name of the option is called up options.
Rendering the Input
Afterward, let’s render the input element. On this element, set the class attribute to regular text. The input will have similar attributes to the element from the other page.
Setting the Name Attribute
Next, let’s set the name attribute to the following value: up options OG Title. Here’s where things become different. Normally, we would give our input a custom name. However, we must set the name attribute to the name of the option. WordPress handles processing the form.
Value Attribute
For this reason, the name of our input must match the name of our option. If our option is an array, we need to add a pair of square brackets to specify the item in the array. The last attribute will be the value attribute we should output. Echo the options OG title variable with the escape attribute function.
Testing the Input
Let’s test our input before adding the other inputs in the browser. Refresh the page. Our input appears in the section with the original value of the option. Great.
Adding Additional Fields
Let’s try adding the other fields to our form. The process is going to be very similar. Back in the editor, let’s make three copies of the add settings field function. In total, we are going to have four fields.
Updating Field Names
Each copy should reflect an option from our plugin. Let’s update these fields first. The second field can be updated by changing the word title to image. Next, change the third field by changing the word title to description. Lastly, change the fourth field by changing the word title to enable.
Defining Additional Rendering Functions
We’re almost done. The last step is to define the function for rendering the inputs of our other fields. To save time, I have prepared these functions for you.
Using Provided Functions
In the resource section of this lecture, I provide a link to a gist. This just contains a list of functions for the inputs. Copy them to your clipboard. Next, paste them into the settings API PHP file.
Similarity of Functions
If you were to look through the functions, you’d notice one thing: they’re very similar to the inputs from the original page. We can safely copy and paste the inputs from the original page to these functions. The modifications I’ve performed on these inputs are by changing the name attribute to the field’s respective option.
Updating the Image Input
Other than that, they’re mostly the same for the image. I’m using the button to change the image. However, this solution will not work. The script for handling the media library will not be enqueued on our page.
Updating the Enqueue File
Let’s update the enqueue PHP file. Inside the conditional statements, and the following condition or hook suffix equals equals equals utility plus page up plugin options alt. Ahead of time, I echoed the hook suffix variable for the other page. The name in our condition is the name assigned by WordPress for our page.
Final Testing
Let’s refresh the page in the browser. As you can see, the fields appear in the section. We can freely modify the values, including the image. After modifying these values, we can submit the form.
Benefits of the Settings API
Like I said before, we do not need to intercept the request. The Settings API is capable of updating our options. This is one of the benefits of using the Settings API. We can avoid processing the request.
Registering New Metadata for Posts
Introduction
We are going to register new metadata for posts. Throughout this section, we’ve created settings for adding an open graph preview for various social media platforms.
Current Limitations
At the moment, the same preview will be generated for all pages. Ideally, the preview should reflect the contents of the page.
Example of Open Graph Preview
Let me show you an example. Currently, I’m using a tool for previewing an open graph preview. I’m going to submit a link to the home page of a random site. This site has an open graph preview. The preview contains a generic title, image, and description.
Specific Product Preview
Let’s check out what happens when I view the preview for a specific product. This time, the preview displays information on the product. It’s common practice to tailor the preview to a specific page. This helps users on social media sites understand the type of content on a page.
Objective
Our plugin should give users the option of modifying the preview for a specific post. That’s what we’ll be tackling next in this section.
Registering New Metadata
To get started, we’re going to register new metadata for a post. The open graph settings for a post will be stored as post metadata in your editor.
Opening the File
Open the recipe post type dot PHP file. In this file, we are registering the recipe post type. In addition, we’re registering metadata for this post type.
Registering Metadata
Let’s register our metadata from within this function at the bottom of the file. Run the register post meta function.
First Argument: Post Type
The first argument of this function is the name of the post type. However, we’re going to apply this metadata to all posts. It shouldn’t be exclusive to a specific post type. Luckily, we can pass in an empty string. WordPress will apply the metadata to all post types.
Setting Metadata Name
Next, let’s set the name of our metadata. It will be called OG title. The fields are going to be similar to the fields from our custom page. Users will be able to modify the title, image, and description of an open graph preview.
Configuring Metadata Settings
After setting the name, let’s configure the settings of this metadata by passing in an array. Let’s set the single item to true. This metadata will contain a single value. We’re not going to store the metadata in an array.
Setting Data Type
Next, let’s set the type item to string. This option will set the data type of our variable. Afterward, set the show in rest option to true. This option will expose the metadata through the REST API.
Sanitization Callback
Up next, set the sanitized callback option to the sanitized text field function. This option is new to us. WordPress can handle updating metadata through the REST API. If the value is updated through a request, we can run the value through a custom function for sanitization.
Using a Default Sanitization Function
Typically, we would define a custom function. However, we’re not going to go heavy on the sanitization. It’ll be enough to pass the value onto the sanitized text field function.
Authorization Callback
The last option is called the off callback. The value for this option will be an anonymous function. If the metadata is added, modified, or deleted through the REST API, we can limit the access to perform these actions.
Checking User Capabilities
The off callback function must return a boolean value. Inside this function, let’s return the current user can function. We’re going to check the user’s capabilities. The name of the capability will be called edit posts. This capability is given to users who can edit a post.
Adjusting Permissions
Most roles have this access. We’re lowering the permissions since most users can create posts but not modify the global settings of a site. If the user can edit a post, they’re allowed to edit the metadata.
Creating Additional Metadata
Let’s create three copies of this function. The values for the other metadata will be similar. We just need to modify the name, which is the value in the second argument of the function.
Modifying Names for Other Metadata
For the second copy, set the name to OG description. For the third copy, set the name to OG image. Lastly, set the fourth copy’s name to OG override image.
Purpose of Override Image
The last option will give the user the ability to override the image of the post by default. We’re going to use the featured image of the post as the image for the preview. However, users may want to use a different image for social media. If that’s the case, we’ll give them the option to override the default behavior.
Setting Metadata Type
For this option, let’s set the type to Boolean. Next, let’s add an option called default with a value of false. The default option gives us the opportunity to set the default value for this metadata.
Testing the Metadata Registration
Our metadata has been registered. Moving on, let’s try testing the metadata by testing the Post’s endpoint. Open the Postman application.
Creating a GET Request
In a new tab, create a GET request with the following URL: udemy local slash wp json slash wp slash v two slash posts. The metadata will be applied to any post type. In this example, we’re going to test the post post type.
Sending the Request
Let’s send the request. In the response body, we will receive an array of objects. Each object represents a single post. Within any of the objects, search for a property called meta. WordPress will store the metadata within this property.
Confirming Metadata Registration
If we look closely, our custom metadata has been added to the response. That’s perfect. We’ve successfully registered our metadata with all post types.
Adding Fields to the Gutenberg Editor
Introduction
We are going to start adding the fields to the Gutenberg editor by creating a script. Unlike before, Gutenberg does not support the Settings API. We must use JavaScript and React to add forms to the page.
Directory Creation
Let’s create a script for adding these fields in the source folder. Create a new directory called BLOCK Editor. We are going to store files related to the editor in this directory.
Purpose of the Directory
Blocks are not our only option for extending the editor. Other areas of the editor can be modified. For example, we can add a custom sidebar. This allows us to add settings that are independent of a block. Files that are not for blocks can be created inside this directory.
File Creation
Let’s create a file called Index.js. Next, let’s create a file called Sidebar.js. The index.js file will be considered the entry point for organization reasons. We are going to separate the code for the sidebar in a separate file from the index file.
Importing Sidebar File
Import the sidebar.js file. Afterward, log a simple message from the sidebar file.
Configuration in Webpack
Next, we should process these files through Webpack. The files we’re creating are not blocks. Therefore, Webpack will not bother processing our files. Open the webpack.config.js file.
Entry Object Modification
Inside the entry object, add a property called BLOCK Editor/Index. These files will be stored in a separate directory from our blocks. Next, let’s set the value to the following: ./source/block-editor.
Restarting the Command
Let’s verify the files are being bundled by restarting the npm run start command in the command line. New entry points will not be picked up by Webpack any time the configuration file is modified. We must always restart the command for the changes to take effect.
Checking the Build Directory
After the command has been restarted, let’s check out the build directory. As expected, the files have been generated.
Open Register Assets File
The last step is to queue these files. Open the register-assets.php file. At the bottom of the file, let’s register the script with the wp_register_script function.
Script Registration
The name of our handle will be called up_editor. The path to the file will be: plugins_url(‘/build/block-editor/index.js’, FILE).
Including Asset File
Next, let’s include the PHP file for this script. It will include the list of dependencies and version info for the scripts above the function. Define a variable called editor_asset with the following value: include(plugin_dir_path(FILE) . ‘build/block-editor/index.asset.php’).
Setting Arguments
After including this file, we can set the third and fourth arguments to editor_asset[‘dependencies’] and editor_asset[‘version’] variables. Lastly, let’s set the fifth argument to true. This argument will force the script to load in the footer. We do not want to block the Gutenberg editor from loading.
Special Hook for Gutenberg
The last step is to queue these files. WordPress has a special hook for queuing files in the Gutenberg Editor. This saves us time for checking the current page.
Implementing the Hook
Open the main plugin file. At the bottom of the hook section, add an action hook called enqueue_block_editor_assets. The name of our function will be called up_enqueue_block_editor_assets.
Creating Editor Assets File
Let’s create a file called editor-assets.php inside the admin folder. Inside this file, define the function from the hook.
Importance of the Conditional Statement
Before enqueueing the files, we should perform a single check. I wasn’t being completely honest. This hook runs for two different types of pages. It will run for the full site editor and the page for editing a post.
Creating the Conditional Statement
These settings should be available for individual posts. It doesn’t make sense to add fields for modifying a page’s open graph settings from the full site editor. Let’s create a conditional statement for checking the current page.
Getting Current Screen Information
Unfortunately, the hook does not provide the name of the page. There is an alternative solution inside the function. Define a variable called current_screen. The value for this variable will be the get_current_screen() function. This function returns an object with information on the current page, including the name of the page.
Checking for Full Site Editor
You’re more than welcome to output this variable onto the screen. I’ve already done so. To save time, I will provide the name of the page. In a conditional statement, write the following condition: current_screen.base === ‘appearance_page_gutenberg-edit-site’.
Exiting the Function
The object has a property called base. This property contains the type of page. In this example, we’re checking if the page is the full site editor. If it is, we are going to return from the function. This will immediately stop the function from running.
Enqueueing the Script
After the conditional block, let’s enqueue the script with the wp_enqueue_script function. The name of the script is called up_editor.
Testing in the Browser
After enqueueing the script, we can try testing our scripts in the browser. Try viewing a random post with the Gutenberg editor. The script should load for any page.
Checking the Console
Open the console panel from the developer tools. Within the panel, the message from our script will appear. Perfect! We’ve successfully created and included a file for handling the custom fields.
Registering a Sidebar in Gutenberg
Introduction
We are going to register a sidebar in the Gutenberg editor. The sidebar will allow users to modify post metadata directly within the editor interface.
Viewing the Editor
Currently, you should be viewing a random post with the Gutenberg editor. At the top right corner, there’s a button for toggling the sidebar. This sidebar contains the settings for the page or block and can be toggled by clicking on this button.
Opening the Sidebar.js File
Let’s try rendering a sidebar in your editor. Open the sidebar.js file.
Importing Required Functions
- Import
registerPlugin
: At the top of the file, import a function calledregisterPlugin
from the @wordpress/plugins package. This function allows us to register plugins with the Gutenberg editor and render a React component.javascriptCopy codeimport { registerPlugin } from '@wordpress/plugins';
- Import
PluginSidebar
: Next, import a component calledPluginSidebar
from the @wordpress/edit-post package. This component creates the interface for rendering a sidebar.javascriptCopy codeimport { PluginSidebar } from '@wordpress/edit-post';
- Import the
__
Function: Lastly, import the__
function from the @wordpress/i18n package for handling translations.javascriptCopy codeimport { __ } from '@wordpress/i18n';
Registering the Plugin
Now we can begin rendering the sidebar below the import statements. Use the registerPlugin
function.
- Registering the Plugin:javascriptCopy code
registerPlugin('up-sidebar', { render: function() { return ( <PluginSidebar name="up-sidebar" icon="share" title={__('Udemy Plus Sidebar', 'text-domain')} > <p>{__('Your random text here.', 'text-domain')}</p> </PluginSidebar> ); }, });
- First Argument: The name of our plugin is set to
'up-sidebar'
. - Second Argument: An object of configuration settings containing the
render
function.
- First Argument: The name of our plugin is set to
PluginSidebar Properties
- name: Should be unique to avoid conflicts with other sidebars. Set to
'up-sidebar'
. - icon: Set to
'share'
as it’s appropriate for our sidebar, which is related to social media. - title: Displays text at the top of the sidebar. Use translatable text:
__('Udemy Plus Sidebar', 'text-domain')
. - Children: Add random text inside a
<p>
tag for now.
Testing the Sidebar
Refreshing the Page
Before proceeding further, let’s test our sidebar in the browser. Refresh the page.
Sidebar Appearance
At the top right corner of the page, a button with the social icon should appear. Click on this button to open our sidebar.
Rendering Fields for Modifying Post Metadata
Introduction
We will start rendering the fields for modifying the post’s metadata in the Gutenberg editor. These fields will allow users to customize the Open Graph settings for each post.
Step 1: Importing the Necessary Function
Opening the Sidebar.js File
Open the sidebar.js file.
Importing useSelect
At the top of the file, import the useSelect
function from the @wordpress/data package. This function will help us select the metadata from the current post.
javascriptCopy codeimport { useSelect } from '@wordpress/data';
Step 2: Grabbing the Metadata
Using useSelect
In the function that renders the sidebar, run the useSelect
function with an arrow function.
javascriptCopy codeconst meta = useSelect((select) => {
return select('core/editor').getEditedPostAttribute('meta');
}, []);
- This arrow function provides the
select
function for selecting data from the application state. - We use it to retrieve the metadata for the current post.
Structuring the Metadata
Store the following metadata values in a variable for readability:
OG Image
OG Description
OG Override Image
javascriptCopy codeconst ogImage = meta['OG Image'];
const ogDescription = meta['OG Description'];
const ogOverrideImage = meta['OG Override Image'];
Step 3: Rendering the Fields
Using Predefined Components
In the resource section of this lecture, I provided a link to a gist containing components for rendering the fields. These components are familiar as we’ve used them for other blocks.
- Copy the Code: Copy the provided code for the inner components of the sidebar.
- Pasting the Code: Head back to the PluginSidebar component and paste the copied code.
Importing Components
Make sure to import the required components at the top of the page. Add the following import statement:
javascriptCopy codeimport {
PanelBody,
TextControl,
TextareaControl,
ToggleControl,
} from '@wordpress/components';
Step 4: Reviewing Component Structure
Empty OnChange Events
Before previewing our code, note that the components currently have empty onChange
events. In the next lecture, we will implement functionality to update the metadata. For now, the fields will not be modifiable.
Step 5: Previewing the Sidebar
Refreshing the Page
Refresh the page and click on the button to open the sidebar.
Checking Field Visibility
As you can see, there are three fields rendered: the Open Graph image, description, and override image. The only field missing is the image uploader, which we will address in a future lecture.
Dispatching Updates for Post Metadata
Introduction
We will learn how to dispatch updates for modifying the metadata of a post in the Gutenberg editor. Instead of creating custom endpoints or hooks, we will leverage WordPress’s built-in capabilities to update metadata through the REST API.
Step 1: Importing Necessary Functions
Opening the Sidebar.js File
Open the sidebar.js file.
Importing useDispatch
At the top of the file, import the useDispatch
function from the @wordpress/data package. This function will allow us to update the metadata.
javascriptCopy codeimport { useDispatch } from '@wordpress/data';
Step 2: Using useDispatch
Call useDispatch
in the Render Function
Inside the render function, call the useDispatch
function to get access to the dispatch actions.
javascriptCopy codeconst { editPost } = useDispatch('core/editor');
- This will allow us to modify the attributes of the post, including metadata.
Step 3: Modifying the Post Attributes
Updating Metadata on Field Change
We will now set up the metadata updates in the onChange
events of the controls.
- Open Graph Title
- In the
onChange
event of the Open Graph title field, call theeditPost
function.
- In the
javascriptCopy code<TextControl
label="Open Graph Title"
value={ogTitle}
onChange={(value) => editPost({ meta: { 'OG Title': value } })}
/>
- Open Graph Description
- Repeat the process for the Open Graph description field.
javascriptCopy code<TextareaControl
label="Open Graph Description"
value={ogDescription}
onChange={(value) => editPost({ meta: { 'OG Description': value } })}
/>
- Override Image Toggle
- Finally, for the toggle control for overriding the image, update the event as well.
javascriptCopy code<ToggleControl
label="Override Featured Image"
checked={ogOverrideImage}
onChange={(value) => editPost({ meta: { 'OG Override Image': value } })}
/>
Step 4: Testing the Code
Refreshing the Page
After implementing the updates, refresh the page and navigate to a post in the Gutenberg editor.
Observing Field Behavior
You should be able to modify the fields in the sidebar. Although the changes won’t reflect immediately in the post, the update button at the top right corner will light up, indicating that changes are queued for submission.
Step 5: Verifying Updates
Pressing Update
When you press the update button, WordPress will process all queued changes at once.
Checking the Sidebar
After the update, refresh the sidebar. You should see that the new values for the Open Graph metadata have persisted.
Creating a Custom Media Library Interface
Introduction
We will create a custom interface for opening the media library in the Gutenberg editor. Instead of using the Media Placeholder component, we’ll develop our own interface to provide users with the option to select an image for the Open Graph preview.
Step 1: Import Necessary Components
Opening the Sidebar.js File
Open the sidebar.js file.
Importing Components
At the top of the file, import the following components:
javascriptCopy codeimport { MediaUpload, MediaUploadCheck } from '@wordpress/block-editor';
import { Button } from '@wordpress/components';
Step 2: Rendering the Image Selection Interface
Conditional Rendering
In the PanelBody component, we will check if the user wants to use a custom image. If they do, we will render the image selection interface.
- Using Fragment Element
- Wrap the image tag and the media upload component in a Fragment element to allow multiple root elements.
javascriptCopy code<Fragment>
<img src={ogImage} alt="Open Graph Preview" />
<MediaUploadCheck>
{/* Media upload component will go here */}
</MediaUploadCheck>
</Fragment>
- Rendering the Media Upload Component
- Inside the
MediaUploadCheck
, add theMediaUpload
component.
- Inside the
javascriptCopy code<MediaUpload
accept="image/*"
render={({ open }) => (
<Button isPrimary onClick={open}>
Change Image
</Button>
)}
onSelect={(image) => {
editPost({
meta: {
'OG Image': image.sizes.open_graph.url,
},
});
}}
/>
Step 3: Adding Properties to the Media Upload Component
Properties Overview
- accept
- Set this property to allow only image types:
javascriptCopy codeaccept="image/*"
- render
- This property is a function that defines how to render the button that opens the media library. In this case, we’ll return a
Button
component.
- This property is a function that defines how to render the button that opens the media library. In this case, we’ll return a
- onSelect
- This property defines the function to handle the selection of an image. It receives the selected image as an argument and updates the post metadata accordingly.
Step 4: Testing the Code
Refreshing the Page
- Open the custom sidebar.
- Initially, the button for changing the image should be hidden.
- Toggle the override option to reveal the button.
- Click on the button to open the media library.
Selecting an Image
- After selecting an image, update the post. Refresh the page to verify that the selected image persists in the sidebar.
Rendering Open Graph Tags in WordPress
Introduction
We will finalize our solution by rendering Open Graph tags into the head section of the document. This is crucial for ensuring that social media platforms can generate previews of our posts.
Step 1: Add a Hook for the Head Section
Open the Main Plugin File
Open your main plugin file where you handle hooks.
Hook into wp_head
At the bottom of the hook section, add the following:
phpCopy codeadd_action('wp_head', 'up_wp_head');
This action hook will allow us to render content within the head tag of the document.
Step 2: Create the Head Rendering Function
Create the Head PHP File
Inside the includes/front
directory, create a file called head.php.
Define the Function
In this file, define the function up_wp_head
:
phpCopy codefunction up_wp_head() {
$options = get_option('up_options');
if (isset($options['enable_og']) && $options['enable_og'] != 1) {
return;
}
$title = $options['og_title'];
$description = $options['og_description'];
$image = $options['og_image'];
$url = site_url('/');
if (is_single()) {
$post_id = get_the_ID();
$new_title = get_post_meta($post_id, 'og_title', true);
$title = !empty($new_title) ? $new_title : $title;
$new_description = get_post_meta($post_id, 'og_description', true);
$description = !empty($new_description) ? $new_description : $description;
$override_image = get_post_meta($post_id, 'og_override_image', true);
$image = $override_image ? get_post_meta($post_id, 'og_image', true) : get_the_post_thumbnail_url($post_id, 'open_graph');
$url = get_permalink($post_id);
}
// Render the Open Graph tags here
}
Step 3: Render the Open Graph Meta Tags
Adding Meta Tags
After preparing the variables, we can add the meta tags at the bottom of the up_wp_head
function.
phpCopy code echo '<meta property="og:title" content="' . esc_attr($title) . '" />';
echo '<meta property="og:description" content="' . esc_attr($description) . '" />';
echo '<meta property="og:image" content="' . esc_url($image) . '" />';
echo '<meta property="og:type" content="website" />';
echo '<meta property="og:url" content="' . esc_url($url) . '" />';
These meta tags will provide the necessary information for social media platforms to generate a preview of your content.
Step 4: Testing the Implementation
Refresh the Page
After saving your changes, refresh the page in your browser.
- Note: Open Graph previews typically require a live site to be tested properly, as local environments may not generate previews correctly.