
Website development can seem like a complicated and overwhelming aspect of the website design process. If you’re not familiar with coding, chances are, working with data objects will probably feel like reading Ancient Sanskrit. Understanding OOP is essential for any developer looking to manage complex tasks efficiently, especially when working with dynamic content in WordPress.
At Good Agency, we understand how crucial the details of website design and development are to creating seamless and functional user experiences. As Senior Developer at Good Agency, I’m here to walk with you step-by-step into the basics of Object-Oriented Programming (OOP) in WordPress.
The Basics
When you browse the internet, most of the information you see relies on data. A common format for this data is JSON (JavaScript Object Notation). JSON stores data in a way that is easy to read and access. For example, a JSON object for a person might look like this:
{
“name”: “John Doe”,
“email”: “johndoe@example.com”,
“age”: 30
}
In other words, the text, information, photos—almost everything you see—on the internet has a structured data format behind it. This matters because it allows websites to dynamically display content based on various factors, making the user experience more interactive and personalized.
Before diving into the technical details, let’s clarify and define some key concepts:
- Object: A structure that groups data and functions related to a particular concept, making it easier to manage complex programs by keeping related tasks and information in one place.
- Function: A block of code designed to perform a specific task.
- Array: A collection of items stored at contiguous memory locations.
- Variable: A storage location paired with a symbolic name that contains some known or unknown quantity of information referred to as a value.
- Shortcode: A WordPress-specific code that lets you do nifty things with very little effort.
- Conditional Check: A statement that performs different actions based on whether a specified condition is true or false.
- Loop: A sequence of instructions that is continually repeated until a certain condition is reached.
Today, we’ll learn how to use objects within WordPress to interact with data stored in its database. Every WordPress site relies on an SQL database to store essential information for plugins and core functionalities. By querying this data, we can retrieve information in JSON format, which enables us to seamlessly integrate it into the front end of our site.
We’ll create a PHP script that accesses the ‘users’ table using the WordPress function get_users and outputs information about these users in HTML. This will allow us to visualize the data on the front end of a WordPress page. To make this easy to use, we’ll register this function inside a shortcode so we can display the user list anywhere on our site.
Before we start, we will need to add the following code to your theme’s ‘functions.php’ file:
<?php
function users_display() {
// Arguments for get_users()
$args = array(
'role' => 'administrator', // Example: get only subscribers. Remove or change as needed.
// Add additional parameters as needed
);
// The User Query
$users = get_users($args);
// String to hold our user data output
$output = '<div class="user-list">';
// Check if we have users
if (!empty($users)) {
foreach ($users as $user) {
// Customize the output as needed. Here's a simple example:
$output .= '<div class="user">';
$output .= '<h2>' . esc_html($user->display_name) . '</h2>'; // User's display name
// You can retrieve more user information here as needed
$output .= '</div>';
}
} else {
// No users found
$output .= 'No users found.';
}
$output .= '</div>';
return $output;
}
add_shortcode('display_users', 'users_display');
The Breakdown
- 1. Create the Function: First, we’ll create a function that can be called later by the shortcode, named users_display. Inside this function, we’ll construct an arguments array (stored in a variable called $args) to pass into the get_users function.
- 2. Retrieve User Data: Next, we use the get_users function to fetch user data based on the $args we set. The output of get_users is stored in a variable named $users. The $args allow us to filter and select the specific information we want from the database. These arguments can be quite detailed and complex if needed.
- 3. Start Building HTML Output: We then create a new variable called $output, where we start constructing the HTML that the function will return. We begin with a static HTML container for the content that will be dynamically rendered inside it. It’s good practice to use such a container to ensure the content is properly managed in the DOM, even during dynamic changes.
- 4. Check if User Data is Available: Moving into the loop, we reference the $users variable in a conditional check. We use an if statement to say, “if the $users variable is NOT empty, execute the following code block.” This block contains a foreach loop that iterates over each user object found.
- 5. Loop Through User Data: For those new to Object-Oriented Programming, visualizing the data flow might be tricky. To simplify, think of the array of users ($users) retrieved by the get_users function like this:
[ { "display_name": "John", "email": "johndoe@example.com" }, { "display_name": "Laura", "email": "laura@example.com" } ]
The get_users function fetches an array of user objects. When we create the foreach loop, we say, “For each element in the $users array, treat each one as an individual user object.” As the loop goes through all the user objects, we can access each user’s data, like their display_name. - 6. Render User Data: In this tutorial, we focus on rendering only the display_name value for brevity. Inside the loop, we specify more markup with
'div class=”user”'
. The class attributes later allow us to tap into each one of these elements being generated per user and add CSS to control the style. For instance:.user{background-color:black;color:#ff:padding: 2%}
- 7. Handle No User Data: After the if check, there’s an else check that executes if the $users array is empty. Essentially, we say, “if there are users, execute this code block; otherwise, show HTML that says ‘no users found’ and assign that to the output.” If no user objects are found, the code block that concatenates users to the $output variable is bypassed, and instead, a ‘no users found’ message is returned.
- 8. Close the HTML Container: After the if/else conditional check, we close out the container class user-list that we established before. We then return the $output variable, which now holds our dynamically assembled HTML with the user data. Our users_display function is now ready to return data for the shortcode.
- 9. Register the Shortcode: Next, we’ll route this function output through a shortcode for easy use anywhere on our WordPress site. We use the add_shortcode function provided by WordPress, passing in two arguments: the name of the shortcode and the function to retrieve data for it. We name our shortcode display_users and call the users_display function we just created. From here, you can use the shortcode in any simple text block element provided by your theme, preview it, and see the user->display_name output for each user in the HTML generated by the users_display function. The image below shows the output of the users_display function we created. The list of names displayed—Casey Price, Catherine Miller, Clay Vaughan, and so on—are fetched from the WordPress database using the get_users function and then rendered dynamically into the HTML on the webpage. This demonstrates how the shortcode ‘display_users’ integrates seamlessly into a WordPress page to display user information retrieved from the database.
Conclusion
In this blog, we’ve explored the basics of Object-Oriented Programming (OOP) in WordPress. By creating a PHP function that retrieves user data from the WordPress database and displays it using a shortcode, we’ve demonstrated how OOP principles can be applied to manage and display dynamic content on your site. This not only enhances the functionality of your WordPress site but also provides a flexible and efficient way to handle complex data interactions. With these skills, you’re now equipped to further customize and optimize your WordPress projects using OOP techniques. Happy coding!
Good Agency
Ready to take your website to the next level? At Good Agency, we specialize in creating stunning, high-performing websites tailored to your business needs. Our expert team combines cutting-edge design with seamless functionality to deliver a website that not only looks great but also drives results. Whether you’re looking to revamp your existing site or build a new one from scratch, we’ve got you covered. Visit Good Agency today to learn more about our website design services and schedule a consultation. Let us help you create a powerful online presence that sets you apart from the competition!