At this point in this series, we've laid the foundation for our plugin, defined a custom hook, and wired up a perpetual message to show how we can take advantage of said hook.
What we haven't done, though, is implement various message types, allow user input, and display messages based on the result of input the user has provided.
But before we do that, we need to add support for the various message types, a class interface that will support each type of message, and the data structures necessary for storing such messages.
I'm looking forward to continuing with this tutorial, but there are a few things we need to review before hopping back into the source code. Make sure that your system has the following software installed:
And if you're looking for an all-in-one solution, don't forget to give MAMP a try.
As mentioned previously, we're right in the middle of this series. If you've missed any of the previous tutorials, here's what we've covered thus far:
And here's what we'll be reviewing in the final tutorial:
For now, though, we have other work on which to focus.
As we get back to work (and as we've reviewed in previous tutorials), we're going to be looking at the following implementation during this piece of the series:
In this tutorial, we'll begin implementing our Settings Messenger by adding support for errors and success messages as well as covering some points on security.
In the last article, we began working on the Settings Messenger, but only in so far as setting up a function that will perpetually display a success notice whenever our custom page is loaded.
In this tutorial, we're going to add support for errors, warnings, and success messages. We're also going to be displaying them all on screen so we can get a feel for how the messenger will work.
Additionally, we're going to add one more change that will add support for dismissing the notices at the user's discretion.
With this as our plan for the work we need to do in this tutorial, let's get started.
Remember the entire point of the Settings Messenger is to define a way for us to work with custom messages, custom hooks, and the native WordPress API for displaying messages in the context of the WordPress administration area.
To do this, we're going to expand the work we did in the previous tutorial and continue growing our work from there.
Since we started with the success message in the previous tutorial, let's go ahead and pick up with that. Right now, we have a hard-coded method that displays a single method:
<?php public function display_message() { $html = " <div class='notice notice-success'> <p><strong>You have successfully displayed a custom success message.</strong></p> </div><!-- .notice-success --> "; $allowed_html = array( 'div' => array( 'class' => array(), ), 'p' => array(), ); echo wp_kses( $html, $allowed_html ); }
Ideally, we'd like to introduce a data structure that will support multiple messages, a function that will give us access to add however many messages we'd like, and a function that will allow us to render all of the success messages.
First, we'll start with an array. This will be a private attribute of the class, and it will be initialized in the constructor. The initial part of the Settings_Messenger
should now look like this:
<?php class Settings_Messenger { private $success_messages; public function __construct() { $this->success_messages = array(); } }
And as you can see, we've defined exactly what we said, except that we haven't defined a method for adding our own messages, and we haven't defined a message for rendering our messages.
So let's do that now. First, let's add a method that will allow us to add our own messages:
<?php public function add_success_message( $message ) { $this->success_messages[] = sanitize_text_field( $message ); }
Note here that we're using sanitize_text_field
to sanitize the data going into the array. You can make the sanitization as strict or as relaxed as you like. I've opted for this particular method as it helps to get the point across without deviating from the point of the tutorial.
Now let's define a method that will allow us to render the messages on the front-end:
<?php public function get_success_messages() { if ( empty( $this->success_messages ) ) { return; } $html = "<div class='notice notice-success'>"; $html .= '<ul>'; foreach ( $this->success_messages as $message ) { $html .= "<li>$message</li>"; } $html .= '</ul>'; $html .= '</div><!-- .notice-success -->'; $allowed_html = array( 'div' => array( 'class' => array(), ), 'ul' => array(), 'li' => array(), ); echo wp_kses( $html, $allowed_html ); }
Granted, this method can stand to be refactored, and I'll touch on this in the conclusion of this post.
For now, though, let's test this out. Try the following code in the tutsplus-custom-message.php
file and then reload the administration screen that we've used throughout the series thus far.
<?php $messenger = new Settings_Messenger(); $messenger->init(); $messenger->add_success_message( 'This is a test message' ); $messenger->add_success_message( 'This is also a test message, too.' );
Permitting everything has been implemented correctly, you should see something like this:
Luckily, adding the next two message types is very similar to what we've done in this section.
Adding support for warning messages will be almost exactly like what we've done before; however, rather than naming our array and related functions having something to do with success, we'll name them something to do with warnings.
So first, let's add the array to contain our messages:
<?php class Settings_Messenger { private $success_messages; private $warning_messages; public function __construct() { $this->success_messages = array(); $this->warning_messages = array(); } }
Then let's add the functions that will allow us to add warnings to the messenger:
<?php public function add_warning_message( $message ) { $this->warning_messages[] = sanitize_text_field( $message ); }
And finally, let's add a function to display the function when necessary (notice that we're using the notice-warning
class name when creating the div
element):
<?php public function get_warning_messages() { if ( empty( $this->warning_messages ) ) { return; } $html = "<div class='notice notice-warning'>"; $html .= '<ul>'; foreach ( $this->warning_messages as $message ) { $html .= "<li>$message</li>"; } $html .= '</ul>'; $html .= '</div><!-- .notice-warning -->'; $allowed_html = array( 'div' => array( 'class' => array(), ), 'ul' => array(), 'li' => array(), ); echo wp_kses( $html, $allowed_html ); }
Note that how you choose to display this particular set of messages is up to you. You may opt to display this in conjunction with the success messages, or you may opt to display this in a completely separate manner.
For this tutorial, I'm going to keep it simple and display only the warning message at a time. So I'll add the following line of code to the main plugin file:
<?php $messenger->add_warning_message( 'Warning! Danger Will Robinson!' );
I will update the hook in the init method of the Settings_Messenger
:
<?php public function init() { add_action( 'tutsplus_settings_messages', array( $this, 'get_warning_messages' ) ); }
And then I'll refresh the page. Assuming you've followed all of the above code correctly, you should see something almost like this:
If not, double-check your code or download the project file attached to this tutorial, and we'll go from there.
Finally, let's do the same thing for our error messages. We'll be repeating exactly what we've done in the above sections, so this should becoming a bit second nature at this point.
First, we need to add an attribute that will hold the array where we will store our error messages:
<?php class Settings_Messenger { private $success_messages; private $warning_messages; private $error_messages; public function __construct() { $this->success_messages = array(); $this->warning_messages = array(); $this->error_messages = array(); } }
Secondly, we need to add a function that will allow us to add to our list of errors:
<?php public function add_error_message( $message ) { $this->error_messages[] = sanitize_text_field( $message ); }
And then we need to be able to display them:
<?php public function get_error_messages() { if ( empty( $this->error_messages ) ) { return; } $html = "<div class='notice notice-error'>"; $html .= '<ul>'; foreach ( $this->error_messages as $message ) { $html .= "<li>$message</li>"; } $html .= '</ul>'; $html .= '</div><!-- .notice-error -->'; $allowed_html = array( 'div' => array( 'class' => array(), ), 'ul' => array(), 'li' => array(), ); echo wp_kses( $html, $allowed_html ); }
To add your own messages, return to the main plugin file and add the following code:
<?php $messenger->add_error_message( 'Believe what you want. But neither you nor I are special.' ); $messenger->add_error_message( 'In my life, as I was making my way, I always asked the question, am I the most powerful person in the room?' ); $messenger->add_error_message( 'People always told me growing up that it\'s never about the destination. It\'s about the journey. But what if the destination is you?' );
Next, update the init
function in the Settings_Messenger
, and you should see something like this when you refresh the page:
And that's how you add custom messages to your administration page using custom hooks. But we've got one more thing to introduce before wrapping up this article.
Before we conclude, I want to show how we can make our messages dismissible or, more simply put, able to be removed by the user. To do this, we can take advantage of functionality that's already built into WordPress.
Since we were just working on the error messages, I'm going to use the error messages as an example. When building the HTML for the error messages, add one more class name to the div
element that contains the message(s).
That is, add is-dismissible
:
<?php $html = "<div class='notice notice-error is-dismissible'>"; $html .= '<ul>'; foreach ( $this->error_messages as $message ) { $html .= "<li>$message</li>"; } $html .= '</ul>'; $html .= '</div><!-- .notice-error -->';
Easy enough, isn't it? You get an icon that allows the user to click on it and, when they do, the message will disappear.
That's nice functionality that fits well within the WordPress user experience for very, very little work on our end.
Now we have a fairly functional Settings_Messenger
. We can add success messages, error messages, and warning messages. We can dismiss messages. We can manage this all independently of anything WordPress may be doing.
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.
For the purposes of this tutorial, I don't plan on refactoring the code that's in this example. We've walked through this type of material before. Furthermore, the purpose of what we're doing is showing how to work with custom error messages, not how to apply the most advanced object-oriented techniques that we can (though that would be nice, wouldn't it?).
Depending on the feedback I receive for this series, perhaps we'll revisit it and refactor it so we can see just how much work can be done and just how many principles can be applied.
As you wait for the next tutorial to be published, note that 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.
Until then, download the available source code, compare it to what we have here, and be sure to run it on your local machine so you're familiar with what's left as we move into the final part of this series.
14 Best PHP Event Calendar and Booking Scripts
/20 Best WordPress Calendar Plugins and Widgets
/Create a Blog for Each Category or Department in Your WooCommerce Store
/Best Affiliate WooCommerce Plugins Compared
/8 Best WordPress Booking and Reservation Plugins
/Best Exit Popups for WordPress Compared
/Best Exit Popups for WordPress Compared
/12 Best Tab & Accordion WordPress Widgets & Plugins
1 /New Course: Practical React Fundamentals
/20 WordPress Video Plugins and Players to Add Engagement
1 /Short Course: Better Angular App Architecture With Modules
/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
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
/15 Best PHP Event Calendar and Booking Scripts
/Set Up Routing in PHP Applications Using the Symfony Routing Component
1 /Creating Pretty Popup Messages Using SweetAlert2
/Create Interactive Gradient Animations Using Granim.js
/How to Build Complex, Large-Scale Vue.js Apps With Vuex
1 /Creating Stylish and Responsive Progress Bars Using ProgressBar.js
/Set Up an OAuth2 Server Using Passport in Laravel
/Getting Started With Redux: Connecting Redux With React
/Getting Started With Redux: Learn by Example
/Introduction to API Calls With React and Axios
/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 Make a Real-Time Sports Application Using Node.js
/How Laravel Broadcasting Works
/Getting Started With Redux: Why Redux?
/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
/Introduction to the CSS Grid Layout With Examples
1 /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
/Eloquent Mutators and Accessors in Laravel
1 /A Gentle Introduction to HOC in React: Learn by Example
/A Gentle Introduction to Higher-Order Components in React
/Understanding Recursion With JavaScript
/Creating a Blogging App Using Angular & MongoDB: Delete Post
/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
/Persisted WordPress Admin Notices: Part 2
/Create Your First Angular App: Storing and Accessing Data
/Creating Your First Angular App: Basics
/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
/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
/How to Auto Update WordPress Salts
/How to Download Files in Python
/10 Best WordPress Star Rating Plugins
/10 Best HTML5 Sliders for Images and Text
/Creating a Task Manager App Using Ionic: Part 2
/Introduction to Forms in Angular 4: Reactive Forms
/Deferring Tasks in Laravel Using Queues
/Introduction to Forms in Angular 4: Template-Driven Forms
/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
/Understanding ExpressJS Routing
/Inheritance and Extending Objects With JavaScript
/Performant 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
/Single-Page Applications With ngRoute and ngAnimate in AngularJS
/How to Create a Custom Authentication Guard in Laravel
/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
/Build Web Applications Using Node.js
/Stateful vs. Stateless Functional Components in React
/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 Back End: Part 2, React
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 5.5 API
/Bulk Import a CSV File Into MongoDB Using Mongoose With Node.js
/API Authentication With Node.js
/Command Line Basics and Useful Tricks With the Terminal
/Learn Computer Science With JavaScript: Part 3, Loops
/Learn Computer Science With JavaScript: Part 4, Functions
/Learn Computer Science With JavaScript: Part 2, Conditionals
/Learn Computer Science With JavaScript: Part 1, The Basics
/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
/Create Interactive Charts Using Plotly.js, Part 2: Line Charts
/Create Interactive Charts Using Plotly.js, Part 1: Getting Started
/Build a To-Do API With Node, Express, and MongoDB
/Getting Started With End-to-End Testing in Angular Using Protractor
/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
/How to Create a Real-Time Feed Using Phoenix and React
/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
/JavaScript-Based Animations Using Anime.js, Part 2: Parameters
JavaScript-Based Animations Using Anime.js, Part 1: Targets and Properties
/20 Popular WordPress User Interface Elements
/Angular vs. React: 7 Key Features Compared
/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 Body Module
/Getting Started With Matter.js: The Engine and World Modules
/Getting Started With Matter.js: Introduction
/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
Using Celery With Django for Background Task Processing
/Dynamic Page Templates in WordPress, Part 3
/Creating a Grocery List Manager Using Angular, Part 1: Add & Display Items
/New Course: How to Hack Your Own App
/What Is a JavaScript Operator?
/Building Your Startup: Approaching Major Feature Enhancements
/Extending HTML by Creating Custom Tags
/How to Define State With Angular UI-Router
/Dynamic Page Templates in WordPress, Part 2
/Dynamic Page Templates in WordPress, Part 1
1 /Building Your Startup: Securing an API
/How to Draw Bar Charts Using JavaScript and HTML5 Canvas
/What Is WP-CLI? A Beginner’s Guide
/How to Zip and Unzip Files in CodeIgniter
/Programming With Yii2: Building Community With Voting, Comments, and Sharing
/How to Work With Session Data in CodeIgniter
/How to Use the jQuery Function to Select Elements
/How to Create Animations in AngularJS With ngAnimate
/AngularJS Form Validation With ngMessages
/15 Best PHP Calendar, Booking & Events Scripts
/Building Your Startup: Using Routes for Schedule With Me
/A Quick Guide to Dependency Management With Bower
/Using the Twitter API to Tweet Repetitive Content
/Getting Started With Chart.js: Scales
/New Short Course: React State Management With MobX
/Building Your Startup: Leveraging Bootstrap, Ajax, and jQuery
/Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts
/Getting Started With Chart.js: Radar and Polar Area Charts
/How to Set Up a Project in Angular 2
/Getting Started With Chart.js: Line and Bar Charts
/How to Handle Errors & Exceptions in the Yii Framework
/Getting Started With Chart.js: Introduction
3 /Building Your Startup With PHP: Bootstrap Your Home Page
/How to Build a User Tour With Shepherd in JavaScript
/Building With the Twitter API: Analyzing Your Followers
/How to Use the WordPress REST API’s Index Route
/Programming With Yii2: Building a RESTful API
/Uploading With Rails and Carrierwave
/How to Use OmniAuth-Twitter in a Rails Application
/Uploading Files With Rails and Dragonfly
/Making a Sliding Side Navigation Menu for Responsive Designs
/Building With the Twitter API: Creating Friends to Follow
/Building Your Startup: Running Multiple Domains
/Using the Requests Module in Python
5 /Acuity Scheduling Developer Platform: OAuth, Webhooks, and Reporting
/Decoding the Proxy Class in OpenCart
/Acuity Scheduling: Embedding and Developer Integration
1 /Custom Controllers in OpenCart 2
/Building Your Startup: Error Logging
/Acuity Scheduling’s Developer-Friendly Scheduling Service
/New Short Course: Essential Gulp Tasks
/Erlang and Elixir, Part 5: Phoenix Framework
/Add a Website Calendar Using Jalendar 2
/Getting Started With Cassandra: Using CQL API and CQLSH
/Using the New York Times API to Scrape Metadata
1 /New Coffee Break Course: How to Animate Your Angular 2 App
/Make Creating Websites Fun Again With Hugo
/Get a Fake REST API Up and Running Using json-server
/Understanding Nested Routing in React
/Authentication in Rails Using Clearance
/Using Illuminate Database With Eloquent in Your PHP App Without Laravel
New Coffee Break Course: How to Use the Angular 2 HTTP Service
/Get Started Building Your Blog With Parse.js: Migration to Your Own Parse Server
/Building Your Startup: Automatic Time-Zone Detection
/Adding Custom Fields to Simple Products With WooCommerce
/New Coffee Break Course: Reactive Programming With RxJS
/Using Namespaces and Autoloading in WordPress Plugins, Part 4
/New Code eBooks Available for Subscribers
/
harriett What's up, after reading this awesome…