Software Engineering in WordPress, PHP, and Backend Development

Tag: WordPress (Page 2 of 217)

Articles, tips, and resources for WordPress-based development.

One Way to Standardize Structure for Must-Use Plugins

The mu-plugins directory can often become full of various files that have basically been dropped in to solve a particular problem for the particular WordPress installation.

In my experience, these are often useful plugins but they aren’t structured like more standard plugins. That is, mu-plugins often look like a bunch of files dropped in the directory that don’t make a lot of sense unless you read the files. Further, an mu-plugin is often a single file that’s monolithic in nature.

Given the nature of mu-plugins, there’s a case to be made they shouldn’t need to be structured like that. Of course, if you’re building some advanced functionality that is considered must-use, then I think it’s worth building it in such a way that follows modern standards and still works within the mu-plugins structure.

What options are there, though?


I’m sure there are many solutions for how to do this but the way that I’ve found to be cleanest while also allowing me to build plugins in the way I typically do is to maintain a bootstrap file in the mu-plugins directory that references the actual plugin which resides in its own subdirectory.

For example, let’s say I’m building a plugin called acme-solution and the basic file structure looks like something like this:

To drop this into the mu-plugins directory, it’s far too many files as it makes it difficult to maintain along with the rest of the plugins that are present (not to mention the work that may be required when working with a CI/CD app).

So then, I’ll create a bootstrap that looks like this

This obviously is named the same as the acme-solution subdirectory to keep cohesion as high as possible. Then the plugin that resides in acme-solution is structure the same as if it were a standard alone plugin.

And, for what it’s worth, the GitHub repository is structure exactly as you see here. That is:

  • CHANGELOG.md
  • README.md
  • LICENSE
  • composer.json
  • composer.lock
  • src/
  • vendor/

Are included in the repository as well.


Note

  • The vendor directory usually only includes the autoloader. I don’t recommend checking all of the dependencies into the repository unless there’s a good reason to do so.
  • Props to Benjamin Rojas for working with me on coming up with something that’s applicable across a variety of types of mu-plugins.

Why We Don’t Always Need Do Perform an Early Return

There are a lot of opinions on how return statements should work.

  • Some say that there should be a single point of return in a function,
  • Some day we should return as early as possible,
  • Some day multiple return statements are fine,
  • And some say that, when applicable, return as early as possible.

I’m sure I’m missing some, but all of these are ones I’m sure the majority of you have seen. And though I don’t hold either of these to be law, I think there’s a time and a place for each.


I’m a fan of the early return statement. In my mind, the sooner we can determine we don’t need to do the work of a function, the better we just leave.

For example, say we know if we’re not on a certain page, we can go ahead and leave the function:

In this case, it makes sense because:

  1. You only want to perform work on the plugins.php page,
  2. The amount of work to be done in the function is larger than what should ever fit within a conditional.

But there’s an alternative when the amount of work is less than what’s above.

Continue reading

The Term ‘WordPress Adjacent’ Should Be More Precise

Over the last year or so, the term “WordPress adjacent” has become more popular to use. And I get it. There are a lot of us who are still heavily involved with WordPress but who are building tools and/or solutions that may not only interact with WordPress or that start with WordPress and fan out from there.

So that phrase, as they say, has entered the chat. And it’s not a bad phrase, per se. But I think it’s imprecise and I think we can do better. This is important for those of us who write, podcast, speak, and any or all of the above.

This is you, entering the chat. Photo Credit.

First because I believe it’s important for us to be able to clearly define about what we’re talking and how it relates to WordPress. And secondly, so that our audience can follow it.

Imagine thinking you’re going to hear someone talk about building headless applications in WordPress and all that comes with that only to hear that a backend engineer is going to be talking about building a utility that incorporates Google Cloud Functions and custom endpoints to send data to a cloud-based database and to a WordPress database, too.

All of that falls under the umbrella of WordPress Adjacent. And that’s why it’s not good enough. It’s why we need to more more precise.

What Does It Mean to Be WordPress Adjacent?

Starting a more broadly, I would say, at it’s core, being WordPress adjacent refers to individuals or projects closely associated with WordPress, either through direct use or integration with technologies related to the core application.

It’s straightforward enough, but it’s a mouthful, isn’t it? Trying to throw this into a presentation or a podcast and you’re going to lose half your audience.

This person just checked out of your talk. Photo Credit.

Here’s why I say that: In their mind, people already have what it means to be WordPress adjacent. So when what you describe doesn’t map to what they think, it feels like someone is wrong or perhaps being misunderstood.

There’s no reason to feel that way but this is why I think we need a level of precision. Ultimately, there’s a myriad of ways one can be WordPress adjacent.

Lack of Precision is Frustrating (Why Wouldn’t It Be?)

The imprecision of the term WordPress adjacent is both a blessing and a curse. On one hand, it allows for flexibility, acknowledging the diverse roles and projects within the WordPress ecosystem.

On the other, this vagueness can lead to confusion. Imagine trying to explain your job to someone using this term – chances are, you’d end up providing a convoluted explanation that leaves the them more confused than not.

Okay, so How Do We Address It?

In my experience backend engineer, I’ve found myself involved in projects that are WordPress adjacent. And there’s certainly been an uptick in that in the last few years. Further, I’m grateful for it because it allows me to continue to grow as an engineer with learning other technologies, integrating them, and then having them still communicate with WordPress.

Case in point. Imagine, databases with a master and development branches all accessible via PHP or cloud functions.

From developing custom APIs that communicate seamlessly with WordPress installations to creating data systems all of which ultimately increase the functionality of WordPress websites.

Stuff like this orbits WordPress without directly living only within it.

And so that’s how what I do is WordPress adjacent. It may be how the work you do is too. But it’s not the same for all of us.

Clarifying Our Roles

So, how do we address this ambiguity? When we use the term “WordPress adjacent,” we provide a brief explanation of how exactly we are adjacent. Whether it’s through

  • developing plugins,
  • creating bespoke themes,
  • enhancing user experience,
  • building headless front-ends,
  • communicating with third-party APIs and integrating them back into the WordPress application (or vice versa),
  • and so on.

Specifying our roles helps in demystifying the term for others.

Ultimately, it fosters a deeper understanding of the diverse economy that revolves around WordPress.

Clearing Things Up

In technology, clarity is key. And given WordPress is technology, it isn’t exempt from that.

For those of us who work in this space, we have a responsibility to those who read our articles, listen to our podcasts, or attend our talks to clarify our roles. Don’t leave it to them to figure out in the moment.

If you’re going to be using the term in the future – which I personally hope to see more of – let’s at least explain how we’re adjacent.

Use Custom Functions to Determine Which Environment You’re Running Your Code

WordPress provides constants and functions for setting up and checking to see if we’re in development mode.

Specifically, see the following:

But if you’re in a situation in which you’re working on code that’s, say, WordPress-adjacent where it both talks to third-party APIs and services but also sends data to WordPress (or reads data from WordPress), it may be helpful to have another way to determine if your code is running on a local machine.

Use Custom Functions

Case in Point

Perhaps you’re going to be registering a JavaScript file that requires a dependencies that is not available on your local machine. If this is the case, you have a few options:

  1. Find all of the dependencies from the production application and add them to your local machine ignoring whatever side effects may happen,
  2. Remove a call to the dependencies in your code and try to remember to add it back before committing to source code,
  3. Or use a a drop-in function for checking if you’re running the code locally.

Though I know each option has its own tradeoffs, I find myself doing the third option more often than not. All it requires is evaluating the loopback interface and seeing where the script is running.

In the context of PHP, a loopback interface refers to the ability of a script or a server to send requests to itself. So if you check to see if it’s running on 127.0.0.1, which is an IPv4 variation of localhost or ::1 which is the IPv6 variation of localhost then you can determine how to move foward.

A Simple Example

Here’s my example function:

public function isLocalDevelopmentEnvironment()
{
    return (
        0 === strcasecmp('::1', $_SERVER['REMOTE_ADDR']) ||
        0 === strcasecmp('127.0.0.1', $_SERVER['REMOTE_ADDR'])
    );
}

Then if you want to use this when, say, enqueuing JavaScript sources in WordPress, you can set up a conditional for dependencies like this:

$dependencies = ['jquery', 'acme-scripts'];
if ($this->isLocalDevelopmentEnvironment()) {
    $dependencies = ['jquery'];
}

Then you can enqueue the scripts like this:

wp_enqueue_script(
    'acme',
    $this->jsDir . 'omega.js',
    $dependencies,
    \filemtime(__FILE__),
    true
);

Sure, it’s a simple example but there’s much more that can be done with that single helper function regardless of if you’re working with WordPress, Google Cloud Functions, cloud databases, or more.

There are, of course, much more complicated ways in which custom functions can be written and used. The point isn’t about complexity, though. It’s about thinking through when utility functions like this are helpful and when they should be used.

Using Custom Templates with Rewrite Rules in WordPress Plugins

Assume you’re working on a custom WordPress plugin that includes its own template for rendering data. The difference in this template is that it’s not one that you’ll apply to a page or custom post type in WordPress, but it will instead be its own page with access to the WordPress core functions.

This works well enough for a plugin, right? 🙂. Credit.

For example, say you’re generating a report for a given user ID and you want the page to incorporate fonts from Google, perhaps a third-party library, and it look as if it’s not even part of the WordPress core application.

The head element of the page may look something like this:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title><?php echo getName($userId); ?></title>
    <link rel="stylesheet" href="<?php echo getAsset("/lib/reset.css"); ?>">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=PT+Sans">
  </head>

But you there are two other requirements:

  1. You want to access the report through a pretty link that includes the $userId (perhaps something like /information/42
  2. You want to use core functions for getting user metadata through functions like get_user_meta.

To do this, you need to have custom templates with rewrite rules in your WordPress plugin. Again, this is not a custom template in the WordPress sense and you’ll only have as many rewrite rules as you do templates.

Custom Templates with Rewrite Rules

1. The Plugin Structure

This can be structured however you want, but I find it easiest to have the rules set in their own file that’s included in the plugin’s bootstrap file or in the core plugin’s file.

I also think it’s easiest to keep the template in its own template directory where you can also house other templates. The main reason for this being that if you have custom rewrite rules, each rule can map to its own template.

In the example I’m going to give throughout this article, I’m going to have the rules located in the plugin bootstrap file which I’m calling plugin.php and I’m going to have the template in a directory called templates. The template will be called information.php so that it maps to the permalink structure I’m going to set up.

So aim to have:

  • plugin.php in the root of your plugin
  • templates/information.php in the root of your plugin

Note that the information.php template does not need to include the standard WordPress template headers because this isn’t that type of template.

2. The Template

This template can be as involved and complicated or as simple as you like. For the purposes of this post and to keep the code easy to follow, I’m just going to render user’s first name and last name from the user metadata table.

For example:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title><?php echo getName($userId); ?></title>
    <link rel="stylesheet" href="<?php echo getAsset("/lib/reset.css"); ?>">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=PT+Sans">
    <link rel="stylesheet" href="<?php echo getAsset("index.css"); ?>">
  </head>
  <body>
    <div id="container">
        <header>
            <h1>Hello World</h1>
        </header>
        <main>
            <?php echo get_user_meta($userId, 'first_name', true) . ' ' . get_user_meta($userId, 'last_name', true); ?>
        </main>
        <footer>
            <p>&copy; <?php echo date('Y'); ?> Tom McFarlin</p>
        </footer>
    </div><!-- #container -->
  </body>
</html>

Obviously, though, you can mark this up however you find necessary. You can even incorporate additional functions that are in plugin.php or whatever file you want to incorporate additional logic to add functionality to the template.

You may see that I have a getAsset function in the head element of this page. This is what that function looks like in plugin.php:

function getAsset(string $filename)
{
    if (0 < stripos($filename, '.css')) {
        return trailingslashit(plugins_url('acme-info')) . "/assets/css/$filename";
    }

    if (0 < stripos($filename, '.js')) {
        return trailingslashit(plugins_url('acme-info')) . "/assets/js/$filename";
    }
}

This is useful for that I’m doing in a template like this but additional functionality and the reason behind doing this is outside the scope of this article. I’m showing that it can be done.

3. The Rewrite Rules

To set up the custom rewrite rules, you’ll need three functions:

First, set up the rewrite rule whenever the plugin is activated so that it persists as long as the plugin is activated. To do this, set up a function that looks like this:

register_activation_hook(__FILE__, function () {
    add_rewrite_rule(
        '^information/([0-9]+)/?',
        'index.php?user_id=$matches[1]',
        'top'
    );

    flush_rewrite_rules();
});

This will add a rewrite rule whenever the plugin is activated to that you can use information/42 and have it passed to the WordPress core application with the digit representing the ID for the user account you want to retrieve.

We also flush the rewrite rules when the plugin is activated so the new rules take affect.

Next, set up the deactivation hook so the custom rewrite rule is removed and is flushed from the WordPress application so no lingering functionality from the plugin works:

register_deactivation_hook(__FILE__, function () {
    flush_rewrite_rules();
});

Finally, set up the functionality so that it does the following:

  1. Filters the REQUEST_URI and sanitizes the URL,
  2. Separates the URL into parts by running explode on the URL
  3. Verifying the URL is properly structured
  4. Redirecting to the custom information.php template
  5. Handling errors if the file doesn’t exists, the user ID is invalid, or the URL is invalid.

It’s a lot of code for stronger functionality (hence my post on using ChatGPT for writing more secure code) but it should be clear enough given the notes above.

add_action('template_redirect', function () {
    $requestUri = filter_var($_SERVER['REQUEST_URI'], FILTER_SANITIZE_URL);
    $requestUriParts = array_values(array_filter(explode('/', $requestUri)));

    if (
        count($requestUriParts) === 2 &&
        strtolower($requestUriParts[0]) === 'report' &&
        ctype_digit($requestUriParts[1])
    ) {
        $userId = intval($requestUriParts[1]);

        // Validate $userId and ensure it's within an appropriate range
        if ($userId > 0 && $userId <= 1000000) { // Adjust the upper limit as needed
            $templatePath = plugin_dir_path(__FILE__) . 'templates/information.php';

            // Check if the template file exists before including it
            if (file_exists($templatePath)) {
                include $templatePath;
                exit;
            } else {
                // Handle the case where the template file is missing
                die('Report template not found.');
            }
        } else {
            // Handle invalid user IDs
            die('Invalid user ID.');
        }
    } else {
        // Handle invalid URLs
        die('Invalid URL.');
    }
});

At this point, assuming you’re trying to access https://yourEnvironment.com/information/42 then you’ll be redirected to the custom template outlined in the second step above.

Notice that you’re still able to read the userId and you’re able to use built-in WordPress functions to render whatever information you deem necessary for your solution.

References

« Older posts Newer posts »

© 2023 Tom McFarlin

Theme by Anders NorenUp ↑