In this series, we've taken a look at how we can implement a system that allows us to programmatically define custom messages that display on a given administration page in the WordPress back end.
If you've followed along with the series thus far, then you know:
As mentioned in the previous tutorial:
But if you've read any of my previous tutorials, you know that I'm not a fan of having duplicated code. Nor am I fan of having one class do many things. And, unfortunately, that's exactly that we're doing here.
And we're going to address that in this final tutorial. By the end, we'll have a complete refactored solution that uses some intermediate object-oriented principles like inheritance. We'll also have a few methods that we can use programmatically or that can be registered with the WordPress hook system.
At this point you should know exactly what you need in your local development environment. Specifically, you should have the following:
I also recommend the most recent version of the source code as it will allow you to walk through all of the changes that we're going to make. If you don't have it, that's okay, but I recommend reading back over the previous tutorials before going any further.
As you may recall (or have ascertained from the comment above), the previous tutorial left us with a single class that was doing too much work.
One way to know this is that if you were to describe what the class was doing, you wouldn't be able to give a single answer. Instead, you'd have to say that it was responsible for handling success messages, warning messages, error messages, and rendering all of them independently of one another.
And though you might make the case that it was "managing custom messages," you wouldn't necessarily be describing just how verbose the class was. That's what we hope to resolve in this tutorial.
Specifically, we're going to be looking at doing the following:
We have our work cut out for us, so let's go ahead and get started with all of the above.
When it comes to refactoring our work, it helps to know exactly what it is that we want to do. In our case, we recognize that we have a lot of duplicate code that could be condensed.
Furthermore, we have three different types of messages managed in exactly the same way save for how they are rendered. And in that instance, it's an issue of the HTML class attributes.
Thus, we can generalize that code to focus on a specific type, and we can consolidate a lot of the methods for adding success messages or retrieving error messages by generalizing a method to recognize said type.
Ultimately, we will do that. But first, some housekeeping.
In the previous tutorials, we've been working with a class called Settings_Messenger
. Up to this point, it has served its purpose, but we're going to be refactoring this class throughout the remainder of this tutorial.
When it comes to this type of refactoring, it's easy to want to simply delete the class and start over. There are times in which this is appropriate, but this is not one of them. Instead, we're going to take that class and refactor what's already there.
All of that to say, don't delete the file and get started with a new one. Instead, track with what we're doing throughout this tutorial.
First, let's introduce a Settings_Message
class. This represents any type of settings message with which we're going to write. That is, it will manage success messages, error messages, and warning messages.
To do this, we'll define the class, introduce a single property, and then we'll instantiate it in the constructor. Check out this code, and I'll explain a bit more below:
<?php class Settings_Message { private $messages; public function __construct() { $this->messages = array( 'success' => array(), 'error' => array(), 'warning' => array(), ); } }
Notice that we've created a private attribute, $messages
. When the class is instantiated, we create a multidimensional array. Each index, identified either by success
, error
, or warning
, refers to its own array in which we'll be storing the corresponding messages.
Next, we need to be able to add a message, get a message, and get all of the messages. I'll discuss each of these in more detail momentarily.
First, let's look at how we're adding messages:
<?php public function add_message( $type, $message ) { $message = sanitize_text_field( $message ); if ( in_array( $message, $this->messages[ $type ] ) ) { return; } array_push( $this->messages[ $type ], $message ); }
This message first takes the incoming string and sanitizes the data. Then it checks to see if it already exists in the success messages. If so, it simply returns. After all, we don't want duplicate messages.
Otherwise, it adds the message to the collection.
Retrieving messages comes in two forms:
Remember, there are times where we may only want to display warning messages. Other times, we may want to display all of the messages. Since there are two ways of doing this, we can leverage one and then take advantage of it in other another function.
Sound confusing? Hang with me and I'll explain all of it. The first part we're going to focus on is how to render messages by type (think success, error, or warning). Here's the code for doing that (and it should look familiar):
<?php public function get_messages( $type ) { if ( empty( $this->messages[ $type ] ) ) { return; } $html = "<div class='notice notice-$type is-dismissible'>"; $html .= '<ul>'; foreach ( $this->messages[ $type ] as $message ) { $html .= "<li>$message</li>"; } $html .= '</ul>'; $html .= '</div><!-- .notice-$type -->'; $allowed_html = array( 'div' => array( 'class' => array(), ), 'ul' => array(), 'li' => array(), ); echo wp_kses( $html, $allowed_html ); }
Notice here that we're using much of the same code from the previous tutorial; however, we've generalized it so that it looks at the incoming $type
and dynamically applies it to the markup.
This allows us to have a single function for rendering our messages. This isn't all, though. What about the times we want to get all messages? This could be to render on a page or to grab them programmatically for some other processing.
To do this, we can introduce another function:
<?php public function get_all_messages() { foreach ( $this->messages as $type => $message ) { $this->get_messages( $type ); } }
This message should be easy enough to understand. It simply loops through all of the messages we have in our collection and calls the get_messages
function we outlined above.
It still renders them all together (which we'll see one use of them in our implementation of a custom hook momentarily). If you wanted to use them for another purpose, you could append the result into a string and return it to the caller, or perform some other programmatic function.
This is but one implementation.
That does it for the actual Settings_Message
class. But how do we communicate with it? Sure, we can talk to it directly, but if there's an intermediate class, we have some control over what's returned to us without adding more responsibility to the Settings_Message
class, right?
Enter the Settings_Messenger
. This class is responsible for allows us to read and write settings messages. I think a case could be made that you could split this up into two classes by its responsibility because it both reads and writes but, like a messenger who sends and receives, that's the purpose of this class.
The initial setup of the class is straightforward.
Settings_Message
class that we can use to send and receive messages.tutsplus_settings_messages
hook we defined in a previous tutorial.Take a look at the first couple of methods:
<?php class Settings_Messenger { private $message; public function __construct() { $this->message = new Settings_Message(); } public function init() { add_action( 'tutsplus_settings_messages', array( $this, 'get_all_messages' ) ); } }
Remember from earlier in this tutorial, we have the hook defined in our view which can be found in settings.php
. For the sake of completeness, it's listed here:
<div class="wrap"> <h1><?php echo esc_html( get_admin_page_title() ); ?></h1> <?php do_action( 'tutsplus_settings_messages' ); ?> <p class="description"> We aren't actually going to display options on this page. Instead, we're going to use this page to demonstration how to hook into our custom messenger. </p><!-- .description --> </div><!-- .wrap -->
Notice, however, that this particular hook takes advantage of the get_all_messages
method we'll review in a moment. It doesn't have to use this method. Instead, it could be used to simply render success messages or any other methods that you want to use.
Creating the functions to add messages is simple as these functions require a type and the message itself. Remember, the Settings_Message
takes care of sanitizing the information so we can simply pass in the incoming messages.
See below where we're adding success, warning, and error messages:
<?php public function add_success_message( $message ) { $this->add_message( 'success', $message ); } public function add_warning_message( $message ) { $this->add_message( 'warning', $message ); } public function add_error_message( $message ) { $this->add_message( 'error', $message ); }
It's easy, isn't it?
Retrieving messages isn't much different except we just need to provide the type of messages we want to retrieve:
<?php public function get_success_messages() { echo $this->get_messages( 'success' ); } public function get_warning_messages() { echo $this->get_messages( 'warning' ); } public function get_error_messages() { echo $this->get_messages( 'error' ); }
Done and done, right?
Notice that the messages above all refer to two other methods we haven't actually covered yet. These are private messages that help us simplify the calls above.
Check out the following private methods both responsible for adding and retrieving messages straight from the Settings_Message
instance maintained on the messenger object:
<?php private function add_message( $type, $message ) { $this->message->add_message( $type, $message ); } private function get_messages( $type ) { return $this->message->get_messages( $type ); }
And that wraps up the new Settings_Messenger
class. All of this is much simpler, isn't it?
It does raise the question, though: How do we start the plugin now that we've had all of these changes?
See the entire function below:
<?php add_action( 'plugins_loaded', 'tutsplus_custom_messaging_start' ); /** * Starts the plugin. * * @since 1.0.0 */ function tutsplus_custom_messaging_start() { $plugin = new Submenu( new Submenu_Page() ); $plugin->init(); $messenger = new Settings_Messenger(); $messenger->init(); $messenger->add_success_message( 'Nice shot kid, that was one in a million!' ); $messenger->add_warning_message( 'Do not go gently into that good night.' ); $messenger->add_error_message( 'Danger Will Robinson.' ); }
And that's it.
A few points to note:
Settings_Messenger
, then you don't have to worry about displaying any messages in on your settings page.Settings_Messenger
, but it doesn't actually retrieve any because I am using the init method.That's all for the refactoring. This won't work exactly out of the box as there is still some code needed to load all of the PHP files required to get the plugin working; however, the code above focuses on the refactoring which is the point of this entire tutorial.
For a full working version of this tutorial and complete source code that does work out of the box, please download the source code attached to this post on the right sidebar.
I hope that over the course of this material you picked up a number of new skills and ways to approach WordPress development. When looking over the series, we've covered a lot:
As usual, I'm also always happy to answer questions via the comments, and you can also check out my blog and follow me on Twitter. I usually talk all about software development within WordPress and tangential topics, as well. If you're interested in more WordPress development, don't forget to check out my previous series and tutorials, and the other WordPress material we have here on Envato Tuts+.
The Best Small Business Web Designs by DesignRush
/Create Modern Vue Apps Using Create-Vue and Vite
/Pros and Cons of Using WordPress
/How to Fix the “There Has Been a Critical Error in Your Website” Error in WordPress
/How To Fix The “There Has Been A Critical Error in Your Website” Error in WordPress
/How to Create a Privacy Policy Page in WordPress
/How Long Does It Take to Learn JavaScript?
/The Best Way to Deep Copy an Object in JavaScript
/Adding and Removing Elements From Arrays in JavaScript
/Create a JavaScript AJAX Post Request: With and Without jQuery
/5 Real-Life Uses for the JavaScript reduce() Method
/How to Enable or Disable a Button With JavaScript: jQuery vs. Vanilla
/How to Enable or Disable a Button With JavaScript: jQuery vs Vanilla
/Confirm Yes or No With JavaScript
/How to Change the URL in JavaScript: Redirecting
/15+ Best WordPress Twitter Widgets
/27 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/21 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/30 HTML Best Practices for Beginners
/31 Best WordPress Calendar Plugins and Widgets (With 5 Free Plugins)
/25 Ridiculously Impressive HTML5 Canvas Experiments
/How to Implement Email Verification for New Members
/How to Create a Simple Web-Based Chat Application
/30 Popular WordPress User Interface Elements
/Top 18 Best Practices for Writing Super Readable Code
/Best Affiliate WooCommerce Plugins Compared
/18 Best WordPress Star Rating Plugins
/10+ Best WordPress Twitter Widgets
/20+ Best WordPress Booking and Reservation Plugins
/Working With Tables in React: Part Two
/Best CSS Animations and Effects on CodeCanyon
/30 CSS Best Practices for Beginners
/How to Create a Custom WordPress Plugin From Scratch
/10 Best Responsive HTML5 Sliders for Images and Text… and 3 Free Options
/16 Best Tab and Accordion Widget Plugins for WordPress
/18 Best WordPress Membership Plugins and 5 Free Plugins
/25 Best WooCommerce Plugins for Products, Pricing, Payments and More
/10 Best WordPress Twitter Widgets
1 /12 Best Contact Form PHP Scripts for 2020
/20 Popular WordPress User Interface Elements
/10 Best WordPress Star Rating Plugins
/12 Best CSS Animations on CodeCanyon
/12 Best WordPress Booking and Reservation Plugins
/12 Elegant CSS Pricing Tables for Your Latest Web Project
/24 Best WordPress Form Plugins for 2020
/14 Best PHP Event Calendar and Booking Scripts
/Create a Blog for Each Category or Department in Your WooCommerce Store
/8 Best WordPress Booking and Reservation Plugins
/Best Exit Popups for WordPress Compared
/Best Exit Popups for WordPress Compared
/11 Best Tab & Accordion WordPress Widgets & Plugins
/12 Best Tab & Accordion WordPress Widgets & Plugins
1 /New Course: Practical React Fundamentals
/Preview Our New Course on Angular Material
/Build Your Own CAPTCHA and Contact Form in PHP
/Object-Oriented PHP With Classes and Objects
/Best Practices for ARIA Implementation
/Accessible Apps: Barriers to Access and Getting Started With Accessibility
/Dramatically Speed Up Your React Front-End App Using Lazy Loading
/15 Best Modern JavaScript Admin Templates for React, Angular, and Vue.js
/15 Best Modern JavaScript Admin Templates for React, Angular and Vue.js
/19 Best JavaScript Admin Templates for React, Angular, and Vue.js
/New Course: Build an App With JavaScript and the MEAN Stack
/Hands-on With ARIA: Accessibility Recipes for Web Apps
/10 Best WordPress Facebook Widgets
13 /Hands-on With ARIA: Accessibility for eCommerce
/New eBooks Available for Subscribers
/Hands-on With ARIA: Homepage Elements and Standard Navigation
/Site Accessibility: Getting Started With ARIA
/How Secure Are Your JavaScript Open-Source Dependencies?
/New Course: Secure Your WordPress Site With SSL
/Testing Components in React Using Jest and Enzyme
/Testing Components in React Using Jest: The Basics
/15 Best PHP Event Calendar and Booking Scripts
/Create Interactive Gradient Animations Using Granim.js
/How to Build Complex, Large-Scale Vue.js Apps With Vuex
1 /Examples of Dependency Injection in PHP With Symfony Components
/Set Up Routing in PHP Applications Using the Symfony Routing Component
1 /A Beginner’s Guide to Regular Expressions in JavaScript
/Introduction to Popmotion: Custom Animation Scrubber
/Introduction to Popmotion: Pointers and Physics
/New Course: Connect to a Database With Laravel’s Eloquent ORM
/How to Create a Custom Settings Panel in WooCommerce
/Building the DOM faster: speculative parsing, async, defer and preload
1 /20 Useful PHP Scripts Available on CodeCanyon
3 /How to Find and Fix Poor Page Load Times With Raygun
/Introduction to the Stimulus Framework
/Single-Page React Applications With the React-Router and React-Transition-Group Modules
12 Best Contact Form PHP Scripts
1 /Getting Started With the Mojs Animation Library: The ShapeSwirl and Stagger Modules
/Getting Started With the Mojs Animation Library: The Shape Module
/Getting Started With the Mojs Animation Library: The HTML Module
/Project Management Considerations for Your WordPress Project
/8 Things That Make Jest the Best React Testing Framework
/Creating an Image Editor Using CamanJS: Layers, Blend Modes, and Events
/New Short Course: Code a Front-End App With GraphQL and React
/Creating an Image Editor Using CamanJS: Applying Basic Filters
/Creating an Image Editor Using CamanJS: Creating Custom Filters and Blend Modes
/Modern Web Scraping With BeautifulSoup and Selenium
/Challenge: Create a To-Do List in React
1 /Deploy PHP Web Applications Using Laravel Forge
/Getting Started With the Mojs Animation Library: The Burst Module
/10 Things Men Can Do to Support Women in Tech
/A Gentle Introduction to Higher-Order Components in React: Best Practices
/Challenge: Build a React Component
/A Gentle Introduction to HOC in React: Learn by Example
/A Gentle Introduction to Higher-Order Components in React
/Creating Pretty Popup Messages Using SweetAlert2
/Creating Stylish and Responsive Progress Bars Using ProgressBar.js
/18 Best Contact Form PHP Scripts for 2022
/How to Make a Real-Time Sports Application Using Node.js
/Creating a Blogging App Using Angular & MongoDB: Delete Post
/Set Up an OAuth2 Server Using Passport in Laravel
/Creating a Blogging App Using Angular & MongoDB: Edit Post
/Creating a Blogging App Using Angular & MongoDB: Add Post
/Introduction to Mocking in Python
/Creating a Blogging App Using Angular & MongoDB: Show Post
/Creating a Blogging App Using Angular & MongoDB: Home
/Creating a Blogging App Using Angular & MongoDB: Login
/Creating Your First Angular App: Implement Routing
/Persisted WordPress Admin Notices: Part 4
/Creating Your First Angular App: Components, Part 2
/Persisted WordPress Admin Notices: Part 3
/Creating Your First Angular App: Components, Part 1
/How Laravel Broadcasting Works
/Persisted WordPress Admin Notices: Part 2
/Create Your First Angular App: Storing and Accessing Data
/Persisted WordPress Admin Notices: Part 1
/Error and Performance Monitoring for Web & Mobile Apps Using Raygun
/Using Luxon for Date and Time in JavaScript
7 /How to Create an Audio Oscillator With the Web Audio API
/How to Cache Using Redis in Django Applications
/20 Essential WordPress Utilities to Manage Your Site
/Introduction to API Calls With React and Axios
/Beginner’s Guide to Angular 4: HTTP
/Rapid Web Deployment for Laravel With GitHub, Linode, and RunCloud.io
/Beginners Guide to Angular 4: Routing
/Beginner’s Guide to Angular 4: Services
/Beginner’s Guide to Angular 4: Components
/Creating a Drop-Down Menu for Mobile Pages
/Introduction to Forms in Angular 4: Writing Custom Form Validators
/10 Best WordPress Booking & Reservation Plugins
/Getting Started With Redux: Connecting Redux With React
/Getting Started With Redux: Learn by Example
/Getting Started With Redux: Why Redux?
/Understanding Recursion With JavaScript
/How to Auto Update WordPress Salts
/How to Download Files in Python
/Eloquent Mutators and Accessors in Laravel
1 /10 Best HTML5 Sliders for Images and Text
/Site Authentication in Node.js: User Signup
/Creating a Task Manager App Using Ionic: Part 2
/Creating a Task Manager App Using Ionic: Part 1
/Introduction to Forms in Angular 4: Reactive Forms
/Introduction to Forms in Angular 4: Template-Driven Forms
/24 Essential WordPress Utilities to Manage Your Site
/25 Essential WordPress Utilities to Manage Your Site
/Get Rid of Bugs Quickly Using BugReplay
1 /Manipulating HTML5 Canvas Using Konva: Part 1, Getting Started
/10 Must-See Easy Digital Downloads Extensions for Your WordPress Site
/22 Best WordPress Booking and Reservation Plugins
/Understanding ExpressJS Routing
/15 Best WordPress Star Rating Plugins
/Creating Your First Angular App: Basics
/Inheritance and Extending Objects With JavaScript
/Introduction to the CSS Grid Layout With Examples
1Performant Animations Using KUTE.js: Part 5, Easing Functions and Attributes
Performant Animations Using KUTE.js: Part 4, Animating Text
/Performant Animations Using KUTE.js: Part 3, Animating SVG
/New Course: Code a Quiz App With Vue.js
/Performant Animations Using KUTE.js: Part 2, Animating CSS Properties
Performant Animations Using KUTE.js: Part 1, Getting Started
/10 Best Responsive HTML5 Sliders for Images and Text (Plus 3 Free Options)
/Single-Page Applications With ngRoute and ngAnimate in AngularJS
/Deferring Tasks in Laravel Using Queues
/Site Authentication in Node.js: User Signup and Login
/Working With Tables in React, Part Two
/Working With Tables in React, Part One
/How to Set Up a Scalable, E-Commerce-Ready WordPress Site Using ClusterCS
/New Course on WordPress Conditional Tags
/TypeScript for Beginners, Part 5: Generics
/Building With Vue.js 2 and Firebase
6 /Best Unique Bootstrap JavaScript Plugins
/Essential JavaScript Libraries and Frameworks You Should Know About
/Vue.js Crash Course: Create a Simple Blog Using Vue.js
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 5.5 API
/API Authentication With Node.js
/Beginner’s Guide to Angular: Routing
/Beginners Guide to Angular: Routing
/Beginner’s Guide to Angular: Services
/Beginner’s Guide to Angular: Components
/How to Create a Custom Authentication Guard in Laravel
/Learn Computer Science With JavaScript: Part 3, Loops
/Build Web Applications Using Node.js
/Learn Computer Science With JavaScript: Part 4, Functions
/Learn Computer Science With JavaScript: Part 2, Conditionals
/Create Interactive Charts Using Plotly.js, Part 5: Pie and Gauge Charts
/Create Interactive Charts Using Plotly.js, Part 4: Bubble and Dot Charts
Create Interactive Charts Using Plotly.js, Part 3: Bar Charts
/Awesome JavaScript Libraries and Frameworks You Should Know About
/Create Interactive Charts Using Plotly.js, Part 2: Line Charts
/Bulk Import a CSV File Into MongoDB Using Mongoose With Node.js
/Build a To-Do API With Node, Express, and MongoDB
/Getting Started With End-to-End Testing in Angular Using Protractor
/TypeScript for Beginners, Part 4: Classes
/Object-Oriented Programming With JavaScript
/10 Best Affiliate WooCommerce Plugins Compared
/Stateful vs. Stateless Functional Components in React
/Make Your JavaScript Code Robust With Flow
/Build a To-Do API With Node and Restify
/Testing Components in Angular Using Jasmine: Part 2, Services
/Testing Components in Angular Using Jasmine: Part 1
/Creating a Blogging App Using React, Part 6: Tags
/React Crash Course for Beginners, Part 3
/React Crash Course for Beginners, Part 2
/React Crash Course for Beginners, Part 1
/Set Up a React Environment, Part 4
1 /Set Up a React Environment, Part 3
/New Course: Get Started With Phoenix
/Set Up a React Environment, Part 2
/Set Up a React Environment, Part 1
/Command Line Basics and Useful Tricks With the Terminal
/How to Create a Real-Time Feed Using Phoenix and React
/Build a React App With a Laravel Back End: Part 2, React
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 9 API
/Creating a Blogging App Using React, Part 5: Profile Page
/Pagination in CodeIgniter: The Complete Guide
/JavaScript-Based Animations Using Anime.js, Part 4: Callbacks, Easings, and SVG
/JavaScript-Based Animations Using Anime.js, Part 3: Values, Timeline, and Playback
/Learn to Code With JavaScript: Part 1, The Basics
/10 Elegant CSS Pricing Tables for Your Latest Web Project
/Getting Started With the Flux Architecture in React
/Getting Started With Matter.js: The Composites and Composite Modules
Getting Started With Matter.js: The Engine and World Modules
/10 More Popular HTML5 Projects for You to Use and Study
/Understand the Basics of Laravel Middleware
/Iterating Fast With Django & Heroku
/Creating a Blogging App Using React, Part 4: Update & Delete Posts
/Creating a jQuery Plugin for Long Shadow Design
/How to Register & Use Laravel Service Providers
2 /Unit Testing in React: Shallow vs. Static Testing
/Creating a Blogging App Using React, Part 3: Add & Display Post
/Creating a Blogging App Using React, Part 2: User Sign-Up
20 /Creating a Blogging App Using React, Part 1: User Sign-In
/Creating a Grocery List Manager Using Angular, Part 2: Managing Items
/9 Elegant CSS Pricing Tables for Your Latest Web Project
/Dynamic Page Templates in WordPress, Part 3
/Angular vs. React: 7 Key Features Compared
/Creating a Grocery List Manager Using Angular, Part 1: Add & Display Items
New eBooks Available for Subscribers in June 2017
/Create Interactive Charts Using Plotly.js, Part 1: Getting Started
/The 5 Best IDEs for WordPress Development (And Why)
/33 Popular WordPress User Interface Elements
/New Course: How to Hack Your Own App
/How to Install Yii on Windows or a Mac
/What Is a JavaScript Operator?
/How to Register and Use Laravel Service Providers
/
waly Good blog post. I absolutely love this…