Throughout this series, we've been creating a plugin that's meant to provide authors with a way to collect, manage, and save ideas and references to content that they're creating within WordPress.
While doing so, we're also looking at ways that we can organize our plugin so that the code and the file organization is clear and maintainable so that as the plugin continues development, we're able to easily add, remove, and maintain its features.
Up to this point, we've put together the basic file organization of the plugin as well as the front-end, but we haven't actually implemented functionality for saving information to the database. And if you can't save information, then the plugin is of little benefit to anyone.
In this post, we're going to hop back into the server-side code and begin implementing the functionality that will:
We've got our work cut out for us. In this article, we're going to be looking at the first two steps and then in the next post, we'll be looking at the final two steps.
In order to verify that the user has the ability to publish to save post meta data, we need to implement a security check during the serialization process. In order to do this, we need to take advantage of a nonce value.
A nonce is a "number used once" to protect URLs and forms from being misused.
In order to introduce one into our meta box, we can implement the functionality in the markup that's responsible for rendering the post template. To do this, load admin/views/authors-commentary-navigation.php
and update the template so that it includes a call to wp_nonce_field
:
<div id="authors-commentary-navigation"> <h2 class="nav-tab-wrapper current"> <a class="nav-tab nav-tab-active" href="javascript:;">Draft</a> <a class="nav-tab" href="javascript:;">Resources</a> <a class="nav-tab" href="javascript:;">Published</a> </h2> <?php // Include the partials for rendering the tabbed content include_once( 'partials/drafts.php' ); include_once( 'partials/resources.php' ); include_once( 'partials/published.php' ); // Add a nonce field for security wp_nonce_field( 'authors_commentary_save', 'authors_commentary_nonce' ); ?> </div>
In the code above, we've introduced a nonce that corresponds to the action of saving the author's commentary (which we've named authors_commentary_nonce
) and associated it with a value that's identified by authors_commentary
.
We'll see where this comes into play momentarily. For now, if you load your browser, you won't see anything new display. That's because the nonce values are displayed in a hidden field.
For those who are curious, you can launch your favorite browser's development tools, inspect the meta box, and you should find something like the following in the markup:
<input type="hidden" id="authors_commentary_nonce" name="authors_commentary_nonce" value="f3cd131d28">
Of course, the value
of your nonce will be different.
In order to make sure the user has permission to save the post, we want to check three things:
We'll write two helper functions to achieve the first and third, and we'll use some built-in functions to check number two (which will actually be used in the second helper function).
First, let's go ahead and setup the hook and the function that will be used to leverage the helper functions and save the meta data. In the constructor for Authors_Commentary_Meta_Box
, add the following line of code:
<?php add_action( 'save_post', array( $this, 'save_post' ) ); ?>
Next, let's define the function. Note that I'm making calls to two functions in the following block of code. We'll be defining them momentarily:
<?php /** * Sanitizes and serializes the information associated with this post. * * @since 0.5.0 * * @param int $post_id The ID of the post that's currently being edited. */ public function save_post( $post_id ) { /* If we're not working with a 'post' post type or the user doesn't have permission to save, * then we exit the function. */ if ( ! $this->is_valid_post_type() || ! $this->user_can_save( $post_id, 'authors_commentary_nonce', 'authors_commentary_save' ) ) { return; } }
Given the code above, we're telling WordPress to fire our save_post
function whenever its save_post
action is called. Inside of the function, we're saying "If the post that's being saved is not a 'post' post type, or if the user does not have permission to save, then exit the function."
Of course, we need to define the functions so that the logic works. First, we'll write the is_valid_post_type
function as a private
function of the current class. It will check the $_POST
array to ensure that the type of post that's being saved is, in fact, a post.
<?php /** * Verifies that the post type that's being saved is actually a post (versus a page or another * custom post type. * * * @since 0.5.0 * @access private * @return bool Return if the current post type is a post; false, otherwise. */ private function is_valid_post_type() { return ! empty( $_POST['post_type'] ) && 'post' == $_POST['post_type']; }
Next, we'll add the user_can_save
function. This is the function that will ensure that the post isn't being saved by WordPress, and that if a user is saving the function, then the nonce value associated with the post action is properly set.
<?php /** * Determines whether or not the current user has the ability to save meta data associated with this post. * * @since 0.5.0 * @access private * @param int $post_id The ID of the post being save * @param string $nonce_action The name of the action associated with the nonce. * @param string $nonce_id The ID of the nonce field. * @return bool Whether or not the user has the ability to save this post. */ private function user_can_save( $post_id, $nonce_action, $nonce_id ) { $is_autosave = wp_is_post_autosave( $post_id ); $is_revision = wp_is_post_revision( $post_id ); $is_valid_nonce = ( isset( $_POST[ $nonce_action ] ) && wp_verify_nonce( $_POST[ $nonce_action ], $nonce_id ) ); // Return true if the user is able to save; otherwise, false. return ! ( $is_autosave || $is_revision ) && $is_valid_nonce; }
Notice here that we're passing in the nonce_action
and the nonce_id
that we defined in the template in the first step. We're also using wp_verify_nonce
in conjunction with said information.
This is how we can verify that the post that's being saved is done so by a user that has the proper access and permissions.
Assuming that the user is working with a standard post type and that the s/he has permission to save information, we need to sanitize the data.
To do this, we need to do this following:
After we do this, then we'll look at saving the information for each of the meta boxes. But first, let's work on sanitization. There are a couple of ways that we can go about implementing this. For the purposes of this post, we'll do it in the most straightforward way possible: We'll check for the existence of the information based on its key, then, if it exists, we'll sanitize it.
For experienced programmers, you're likely going to notice some code smells with the code we're about to write. Later in this series, we'll be doing some refactoring to see how we can make the plugin more maintainable so it's all part of the intention of this particular post.
With that said, hop back into the save_post
function.
Since the first tab that exists within the meta box is the Drafts tab, we'll start with it. Notice that it's a textarea
, so the logic that exists for sanitizing that information should be as follows:
Recall that the textarea
is named authors-commentary-drafts
so that we can access it within the $_POST
array. To achieve this, we'll use the following code:
<?php // If the 'Drafts' textarea has been populated, then we sanitize the information. if ( ! empty( $_POST['authors-commentary-drafts'] ) ) { // We'll remove all white space, HTML tags, and encode the information to be saved $drafts = trim( $_POST['authors-commentary-drafts'] ); $drafts = esc_textarea( strip_tags( $drafts ) ); // More to come... }
Simply put, we're checking to see if the information in the $_POST
array is empty. If not, then we'll sanitize the data.
This particular field is a little more form because it's dynamic. That is, the user can have anything from zero-to-many input fields all of which we'll need to manage. Remember that this particular tab is designed to primarily be for URLs so we need to make sure that we're safely sanitizing the information in that way.
First, we need to make one small change to the createInputElement
function that exists within the admin/assets/js/resources.js
file. Specifically, we need to make sure that the name attribute is using an array so that we can properly access it and iterate through it when looking at $_POST
data.
Make sure that the lines of code responsible for creating the actual element looks like this:
// Next, create the actual input element and then return it to the caller $inputElement = $( '<input />' ) .attr( 'type', 'text' ) .attr( 'name', 'authors-commentary-resources[' + iInputCount + ']' ) .attr( 'id', 'authors-commentary-resource-' + iInputCount ) .attr( 'value', '' );
Notice that the key to what we've done lies in the line that updates the name
. Specifically, we're placing the number of inputs an indexes of the array.
Next, hop back into the save_post
function and add the following code (which we'll discuss after the block):
<?php // If the 'Resources' inputs exist, iterate through them and sanitize them if ( ! empty( $_POST['authors-commentary-resources'] ) ) { $resources = $_POST['authors-commentary-resources']; foreach ( $resources as $resource ) { $resource = esc_url( strip_tags( $resource ) ); // More to come... } }
Because we're working with an array of inputs, we need to first check that the array isn't empty. If it's not, then we need to iterate through it because we aren't sure how many inputs we're going to have to manage.
Similar to the previous block, we're doing a basic level of sanitization and escaping. This is something that you can make as aggressive or as relaxed as you'd like. We'll be coming back to this conditional in the next post when it's time to save the data.
This tab is similar to the previous tabs in that we're dealing with an indeterminate number of elements that we need to sanitize. This means that we're going to need to make a small update to the partial responsible for rendering this input.
On the upside, we're only dealing with a checkbox which has a boolean value of being checked or not (or, specifically, 'on' or empty) so sanitizing the information is really easy.
First, let's update the partial. Locate admin/views/partials/published.php
. Next, find the line that defines the input
checkbox and change it so that it looks like this:
<label for="authors-commentary-comment-<?php echo $comment->comment_ID ?>"> <input type="checkbox" name="authors-commentary-comments[<?php echo $comment->comment_ID ?>]" id="authors-commentary-comment-<?php echo $comment->comment_ID ?>" /> This comment has received a reply. </label>
Notice that we've changed the name
attribute so that it uses a an array with an index as its value. Next, we'll hop back into the save_post
function one more time in order to introduce validation on this particular element:
<?php // If there are any values saved in the 'Resources' input, save them if ( ! empty( $_POST['authors-commentary-comments'] ) ) { $comments = $_POST['authors-commentary-comments']; foreach ( $comments as $comment ) { $comment = strip_tags( stripslashes( $comment ) ); // More to come... } }
Just as we've done with the previous pieces of data, we first check to see if the content exists. If so, then we sanitize it to prepare it for saving. If it doesn't then we don't do anything.
At this point, we're positioned to take on the last two points of the series:
Starting in the next post, we'll revisit the code that we've written in this post to see how we can save it to the database and retrieve it from the database in order to display it on the front-end.
Next, we'll move on to refactoring. After all, part of writing maintainable code is making sure that it's well-organized and easily changeable. Since the code that we work with on a day-to-day basis has already been written and could stand to be refactored, we're going to see how to do that by the end of the series.
In the meantime, review the code above, check out the source from GitHub, and leave any questions and comments in the field below.
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
/WordPress Website Maintenance Guide For Beginners
/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
/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
/Getting Started With Django: Newly Updated Course
/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
/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
/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: 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
/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 /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: HTTP
/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
20Creating 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…