Loading...

Follow WPShout — WordPress Development Tutorials and.. on Feedspot

Continue with Google
Continue with Facebook
or

Valid
What is “Thoughtful Code?” →

A sort-of goal of starting my Thoughtful Code hobby site was to use it it say a little more on theory than “here’s how to set up Java projects” or “here are five cool things you didn’t know about PHP.” I love articles like that (and should write more of them), but they don’t speak to the name or concept of what makes code worth writing and what makes it valuable to the word. And that’s something I think about a lot, both in our work here with WordPress, and with my role in Code for Fort Collins.

So today I’m publishing the first in a series of pieces that explore in a bit more detail what I think makes code “good” and also why I find so many of those conversations become useless mires of subjectivity. In short, I think defining the values that you think makes code good must come conceptually prior to asserting that code it good. That sentence, hopefully, did more than prove that I’ve taken a few (too many?) philosophy courses.

Anyway, I think the piece itself works well, but I’m less sold on these ramblings. So I’ll just urge you again to read it. And ask that if you have any thoughts at all I’d love to hear them. This idea is young enough that I’m not over-attached to it, and should be able to listen well.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

One thing every WordPress site should have is a site icon, also called a favicon—the little tiny image that shows up in your browser tabs to let you tell one site from another. A site icon looks like this:

This video Quick Guide walks you through how to change your WordPress site icon. It’s easier now than ever, because WordPress has rolled this feature into the Customizer. And WordPress’s standard site icon uploading process has you covered for all the less common uses of
favicons (such as serving as retina-ready desktop app icons if someone saves a shortcut to your site onto her iPad).

Here’s our video guide on how to set your site icon in WordPress:

Set Favicon (Site Icon) in WordPress - YouTube

And here’s our text guide to the same information:

How to Change the Site Icon of Your WordPress Site
  1. Collect the image that you’ll use as your site icon (if it’s not already on your WordPress site).
  2. Open the Customizer in WordPress. You can click “Customize” along the top bar (if you’re viewing pages on your site), or “Appearance > Customize” in the left-side menu (if you’re in your WordPress admin area).
  3. Open the “Site Identity” panel by clicking it from the initial listing panel.
  4. Open the “Site Icon” section. If it hasn’t been used before on your site you’ll click the “Select Image” button.
  5. There you will select an image already in your image library, or have the ability to upload a new one. (If you’ve ever used WordPress’s media library, this screen should be familiar.)
  6. You will have the ability to crop the image. If it was square, you’ll probably skip this by clicking “Crop Image” without resizing the selection box. (If you do need to crop, drag away.)
  7. With that, you’ll be set. Your browser tab may immediately update with the image. If it doesn’t, but you see something like this, you’re set:

    (Browser caching can be hard to debug, but refresh may fix it for you.)

And that’s how to change your WordPress site icon! Streamlining this process has been one of the default Customizer’s sweetest features. Let us know if you have any questions—we’re happy to help.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
Candy Japan YouTube marketing horror story →

A frustrating marketing tale

Last week I linked my piece on marketing channels, and the importance of testing new channels to see what works. This is a great write-up of a marketing channel experiment – YouTube sponsorships – and how it really didn’t work.

The side-effect is it’s also a great example of how even if you try something that doesn’t work (ie the YouTube sponsorships), if you’re creative you can still get some results out of it (ie this blog post!). The most interesting stat was this one: “On a CPM basis this [YouTube] was actually ten times more expensive than advertising on prime-time TV.”

This post first appeared in MasterWP, a weekly newsletter for WordPress professionals.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
Finer Points of Text Domain in WordPress Internationalization →

This article from Pascal Birchler about text domain in plugins got into some territory I’d not considered. I shouldn’t be surprised, Pascal is very smart, a regular contributor to WordPress itself.

Discussing it in light of a new WP-CLI command that he’s working on to make plugin translation easier, Pascal highlights the idea that a plugin should have a single text domain slug, like my-plugin and that you should use that everywhere in the code. That’s relatively common knowledge among people who both consider themselves developers and know that i18n is short for “internationalization”.

What’s I’d not considered is what you should do what your WordPress plugin either extends and existing plugin, or pulls in some external code automagically for you. That’s where I fould Pascal most interesting:

A similar situation [that you want to *alway* use your plugins text domain] arises when adding customized WooCommerce shop templates to your WordPress theme. Usually you don’t need to add these to your theme unless you really need to change the markup.

Since these templates are coming from the WooCommerce plugin, all localizable strings use the woocommerce text domain. And when you don’t change any of these strings you might consider just keeping the text domain so WordPress will still translate these.

However, not changing the WooCommerce text domain is a bad idea. The reasons are simple:

  1. Strings with a different text domain than your theme’s might not be extracted in the future.
  2. It’s unreliable.
    When WooCommerce changes its templates in a new version, your strings might suddenly not be localized anymore.
  3. You take control away from users.
    Users and translators have no way to translate your customized shop templates.
  4. Context might change.
    When you heavily customize the WooCommerce templates, some of the strings in them might not be 100% accurate anymore. At this point you have to rephrase and use your own text domain anyway.

For the same reasons you shouldn’t use WordPress core strings, without your project’s text domain, in your plugin or theme either.

My take on this broader topic of internationalization in WordPress is called “Making Plugins and Themes Translation Ready,” by the way.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

You might want add new posts without having to log into the WordPress dashboard, or maybe to allow your visitors a way to submit content of their own. You can do it. In this article we’ll cover a few ways you can create a new post form and save its results into a real WordPress post. Submitted posts from the public-side of WordPress site isn’t the right solution to most problems, but it’s helpful in a few specific situations.

The big benefit of hand-rolling a front-end post submission plugin for WordPress is that you can trim all unnecessary features. The big downside is that you’ll be writing code. A few already-written plugin solutions are highlighted in the “Looking for a Complete Front-End Post Submissions Plugin for WordPress?” section. These have the big benefit that if you’re not comfortable with code, or want more robust anti-spam features, you’ll be all set without a lot of complexity you’d otherwise have. But without further-ado let’s get to understanding how to accept user-submitted content onto your WordPress site!

Why You Might (Not) Want to Allow User-Submitted Posts in WordPress

I’m sure someone who is reading this is hoping that they can just get lots of free high quality content on their WordPress site by letting random visitors submit their content. I wouldn’t say that’s not going to happen, but I’d counsel you not to count on it. I think in general you’d get way more spam submissions from bots than you would get content you cared about.

That said, there are a few reasons I’d think you may really want this functionality:

  • You have some contributors to your site who you don’t want to give admin accounts, but who you trust to write good (non-spam content).
  • You’re wanting to allow for the serendipity of the possibility that I’m wrong and that the spam submission will be minimal.
  • You’ll put this feature on an intranet or other private or protected site or page, so that you can easily not sweat the possibility of spammers finding it.
  • You have occasional emails from dedicated readers which would make great posts if you cut yourself out of the process.
Essential Steps for Making a Form for User Submitted Posts in WordPress

Basically, to allow user-submitted content in WordPress, you must first allow the user to submit the content. This is most often done in WordPress with a form plugin like Ninja Forms or Gravity Forms. Those will have extensions that provide the same functionality we’ll build from scratch here. But for (most of) this article we’re gonna keep things at the lowest-common-denominator level. Which means that we’ll process the form ourselves, and create it with a basic WordPress shortcode.

Here’s the basic step to allowing a post to be created from the front-end of a WordPress site:

  1. Create a form by which a user can submit the post title, content, etc.
  2. When the user “submits” the form, catch the input and validate it as reasonable.
  3. With the “caught” input, use WordPress functions to create the post and save it.

Really, those three step are all you need. They leave aside issues of “spam submissions” and other possible complexities. Which are real and important, and if you’re deploying this sort of solution for a client you must consider for their long-term happiness with your solution. But they aren’t needed for a “happy path” technical implementation that works, so we’re going to skip them here.

The Basics of an HTML Form for Allowing User Post Submission

As I said above, step one in allowing the submission of user content from the the front-side of your WordPress site starts with HTML. For us to get the HTML to show up, we’re going to use a shortcode in WordPress. Shortcodes are contained in square-brackets, and can often be single tags that pull in another PHP function. That’s what we’ll do here, so our form will appear on a post, page, or other WordPress content type when someone uses [wpshout_frontend_post]. Here’s the full code.

add_shortcode( 'wpshout_frontend_post', 'wpshout_frontend_post' );
function wpshout_frontend_post() {
    ?>
<div id="postbox">
    <form id="new_post" name="new_post" method="post">

    <p><label for="title">Title</label><br />
        <input type="text" id="title" value="" tabindex="1" size="20" name="title" />
    </p>

    <p>
        <label for="content">Post Content</label><br />
        <textarea id="content" tabindex="3" name="content" cols="50" rows="6"></textarea>
    </p>

    <p><?php wp_dropdown_categories( 'show_option_none=Category&tab_index=4&taxonomy=category' ); ?></p>

    <p><label for="post_tags">Tags</label>

    <input type="text" value="" tabindex="5" size="16" name="post_tags" id="post_tags" /></p>

    <?php wp_nonce_field( 'wps-frontend-post' ); ?>

    <p ><input type="submit" value="Publish" tabindex="6" id="submit" name="submit" /></p>
    
    </form>
</div>
    <?php
}

There’s nothing special with this form really. The most interesting things are the wp_dropdown_categories() and wp_nonce_field() function calls. Because we’re wanting users to set a category (and prevent that dreaded “Uncategorized”, wp_dropdown_categories() creates the list of categories you can select from. You can learn more about the wp_dropdown_categories function on the WordPress Codex.

Everything else you enter into the form will automatically create a new entry, including tags. Make sure no matter what you do, always include the wp_nonce_field(). Verifying nonces is an important WordPress security strategy to prevent what is called a cross-site request forgery (or CSRF) attack. (You can learn more about that in our “WordPress Security Principles” post).

Where Should the Form Submit Its Data To in WordPress?

As written, our shortcode form above will “submit” its data to the same page on which it ran. That can work, and is the simplest overall way to create a form for a shortcode in WordPress. Submitting to either an “Admin-Ajax” or REST API endpoint would also work. But to keep this as simple as possible, we’ll actually just have our above code include a call of our “post saving” function. So what that would look like is the below change to the above code snippet:

add_shortcode( 'wpshout_frontend_post', 'wpshout_frontend_post' );
function wpshout_frontend_post() {
    wpshout_save_post_if_submitted();
    ?>
    <!-- here and below is all the same as above -->

Writing that code would, if we just started executing it, create a fatal error. That’s because we must create the wpshout_save_post_if_submitted function.

Capturing the Input from the Front-End User Post Submission Form

Creating a function to save our front-end user content in WordPress would look a little like that:

function wpshout_save_post_if_submitted() {
    // Stop running function if form wasn't submitted
    if ( !isset($_POST['title']) ) {
        return;
    }

    // Check that the nonce was set and valid
    if( !wp_verify_nonce($_POST['_wpnonce'], 'wps-frontend-post') ) {
        echo 'Did not save because your form seemed to be invalid. Sorry';
        return;
    }

    // Do some minor form validation to make sure there is content
    if (strlen($_POST['title']) < 3) {
        echo 'Please enter a title. Titles must be at least three characters long.';
        return;
    }
    if (strlen($_POST['content']) < 100) {
        echo 'Please enter content more than 100 characters in length';
        return;
    }

    // Add the content of the form to $post as an array
    $post = array(
        'post_title'    => $_POST['title'],
        'post_content'  => $_POST['content'],
        'post_category' => $_POST['cat'], 
        'tags_input'    => $_POST['post_tags'],
        'post_status'   => 'draft',   // Could be: publish
        'post_type' 	=> 'post' // Could be: `page` or your CPT
    );
    wp_insert_post($post);
    echo 'Saved your post successfully! :)';
}

This code is bare-bones, but should help you understand. We start the function wpshout_save_post_if_submitted with four different “guard” clauses. A guard clause prevents an error-y submission from proceeding. That’s what the return statements do. I chose, for simplicity, to echo (or show to the user) any errors, and then return. The core functionality here means that a user will always see the “add a new post” form, and that the success or failure message will appear before that in WordPress. Perhaps this is ideal for you, but it may not be.

To get past the guard clauses, we’d have to have submitted the form and had a nonce set. If you submitted the form you’ll do this easily, but if you’re a bad attacker you will not. Then we just make sure that at least a little about the post got set: that the title was at least three characters long, the post content (or “post body”) was at least 100 characters. That’s pretty short content, but it’s the least we can do to cut down on the various unwanted post drafts we’d otherwise get from spam bots.

Then, if those checks pass, we use the wp_insert_post() function to actually create the post by passing in an associative array of the post content. So the post title will become the post_title element of the $post array. And so on. It’s very noteworthy that our last two lines there are a post_status and post_type. If you wanted to make these frontend user submitted posts publish immediately, you’ll make the status into publish. And you want this form to allow visitors to create WordPress pages instead, you’ll change the post_type to page. (So too with a “custom post type” or CPT that you created already.)

Looking for a Complete Front-End Post Submissions Plugin for WordPress?

As I mentioned above, there are a few big issues with using all the above code. Spam is one of the big ones — our only protection is that if you keep this code making the new posts into drafts, you’ll be protected by them only going live after you’ve approved (“Published”) the drafts.

The other big downside: you’re also forced to write code where good alternative versions exist. Most form plugins–Gravity Forms, Ninja Forms, etc–have this functionality close-at-hand, and there are also a number of plugins that do just this.

Here’re some different ways to accomplish your goal of allowing user-submitted posts on a WordPress website, and how they’re better than our code:

  • User Submitted Posts WordPress plugin (Free) — This works as a shortcode, much like the code we have above. The big advantage it has over our version: USP has built in Google reCAPTCHA and a few other anti-spam measures. While there are other benefits, that one looms large.
  • Tutorial on Creating Posts with Gravity Forms. While Gravity Forms costs money (starting at $59 at the time I write this), it’s a popular plugin and most WordPress developers will already have a copy. Plus, this version will be relatively comfortable to customize for those who already use the Gravity interface.
  • Ninja Forms Front-End Posting Plugin ($39). This is a paid extension to the free Ninja Forms plugin. If you like Ninja Forms already, this has similar advantages to the Gravity Forms option: familiar interface, comfortable controls.

There are a lot of other ways to do this too. At least a few other free plugins I chose not to link, and probably at least a dozen other paid options. If you have a different favorite forms plugin, I’d first look there for if they have this feature of “frontend WordPress content submission” baked in.

You Now Know How to Save WordPress Submitted Posts

We ran through the code required to do a basic form-submission and front-end user submitted post in WordPress first. Hopefully you found some of that content interesting, and useful if you’re bound and determined to do it on your own.

As I said above, I think the times are rare (and generally when you need lots of front-end polish or custom behavior in saving) where you should actually be doing that. For most use case in WordPress today, you’re better off taking advantage of someone else’s work, be it in Ninja Forms, Gravity Forms, WPForms, or the free User Submitted Posts plugin on the WordPress plugin repository. All of those will save you time and energy debugging and fixing issues with the code over time. And that’s a great deal.

Good luck! And may your users write well

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

How to Change WordPress User Passwords via FTP →

A member from the WPShout Facebook Group blew my mind last week with this set of instructions for either resetting WordPress user passwords or adding new users using only an FTP connection. This was in response to our Quick Guide that describes how to do the same thing inside phpMyAdmin, which requires cPanel (or similar) access. For many situations, I believe this FTP route is quite a bit simpler and requires requesting less complete access from your clients.

These FTP password reset tools seem obvious in retrospect—they’re based on PHP functions I’ve known WordPress has—but they had simply never occurred to me. Enjoy!

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
Marketing channels, and how to think about marketing your WordPress business →

Alex on his marketing philosophy.

My day job is doing marketing for WordPress businesses, and I wrote this to explain how I approach marketing strategy, and how this offers an extremely good way of thinking about and running your marketing.

The thesis is as follows: marketing channels are categories of marketing activities, and these range from content marketing to TV ads. You want to identify which channels work for you (even just one is fine!) and then extract as much value as possible from them before adding any more channels.

You try and have as few channels as possible, and this forces you to focus on what works, and lets you easily filter new opportunities. This is so useful because it’s so simple, but it works at any scale – all the way from the newest WordPress plugins to the biggest in the industry. The post gets into more detail: if you run a WordPress business, check it out!

This post first appeared in MasterWP, a weekly newsletter for WordPress professionals.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Last time, we covered the fundamentals of object-oriented programming (OOP) in PHP: what an object is, what a class is, and how they interact.

Today, we’re going to cover an intermediate OOP topic: how class inheritance allows for parent classes and child classes in OO PHP, and why those are useful programming concepts.

Class inheritance is really an “Aha!” moment that builds on the lovely intuitiveness of OOP itself, and adds a simple and powerful new feature: the world’s not only full of objects, but some objects are types of other objects. In other words, a plum and a peach are both kinds of fruit—and now we can say that. In PHP!

Leaving fruit aside, we’re going to extend our Dog class example from the previous article to our discussion of class inheritance. What can we say: we’re Dog people.

Let’s get into it! Here’s an introduction to class inheritance in PHP.

Companion Video: Understanding Class Inheritance (Child and Parent Classes) in Object-Oriented PHP - YouTube

What “Class Inheritance” Means in Object-Oriented PHP

In object-oriented programming, class inheritance refers to the ability of one class to extend—and be a child class of—another class. So right off the bat, here’s some language to get straight:

If class Golden_Retriever extends class Dog, that means that class Golden_Retriever is a child class of class Dog. That also means that class Dog is the parent class (also called the base class) of class Golden_Retriever.

As you can see, class inheritance in OO PHP breaks into two fundamental concepts:

  1. Parent classes (also called “base classes”), which define the properties and methods of both themselves and child classes; and
  2. Child classes, which inherit properties and methods from parent classes.

Let’s look at an example that spells out this relationship in detail, and starts to get into the object-oriented PHP code that defines parent and child classes.

Code Example: Dog, Catahoula_Dog, and Golden_Retriever_Dog Classes

We’ll step through an example with one parent class, Dog, and two child classes, Catahoula_Dog and Golden_Retriever_Dog, giving code examples for each.

The Parent Class: Dog

From our last article, we’ve got a simple class, Dog. Here’s the code to register it:

class Dog {
    public $color;
    private $noiselevel;

    public function bark() {
        if( $this->noiselevel === 'loud' ) :
                echo 'BARK';
        else :
                echo 'arf';
        endif;
    }
}

That’s our base class or parent class. It’s the “blueprint” for any number of Dog objects that you would create with $fido = new Dog();, each of whom has a color and can bark either loudly or softly.

Is good doggo.

Our First Child Class: Catahoula_Dog

Of course, there aren’t just “dogs” in the world: there are lots of types of dogs. These types, while all having the basic properties and behaviors of a dog, are also unique in many different ways.

For example, where Fred lives, in Louisiana, they have a breed of dog called a Catahoula that has a special property: a really amazingly patterned coat.

Catahoula is a type of dog. It inherits everything that’s always true about dogs (they have a color and can bark), but it adds something on top: a new property (a coat pattern).

Here’s how that looks in code:

class Catahoula_Dog extends Dog {
    public $coat_patterns = array( 'spots', 'stripes', 'other' ); 
}

Are you serious

The magic keyword in the code above is extends. Our child class, Catahoula_Dog, is a child class that extends its parent class, Dog. When we write that magic extends keyword, something critical happens: Catahoula_Dog inherits all the properties and methods of the Dog parent class.

Let’s give you some code to show what we mean:

class Catahoula_Dog extends Dog {
    public $coat_patterns = array( 'spots', 'stripes', 'other' ); 
}

$rover = new Catahoula_Dog();
$patterns = $rover->coat_patterns; // $patterns is now an array containing 'spots', 'stripes', 'other'
$rover->bark(); // Prints "arf" (!)

Whoa! How did we get Rover to bark? bark() is not a method we defined in the Catahoula_Dog class.

The answer—and this is the magic of class inheritance—is that Rover inherited the bark() method from Catahoula_Dog‘s parent class, Dog.

Make sense? Let’s give a second example.

Our Second Subclass: Golden_Retriever_Dog

Of course, there are other types of dog than just Catahoulas. How about golden retrievers? Like any dog, they have a color and can bark, but they’ve also got a special property: huge floppy ears. Beyond that, they’ve got a special method: a strong instinct to fetch() things.

class Golden_Retriever_Dog extends Dog {
    public $ear_shape = 'floppy';

    public fetch( $thrown_thing ) {
        return 'Here is ' . $thrown_thing . '!!!';
    }
}

Hnnnnggg

Now, what’s the effect of registering a property and method only in this child class? Let’s have a look:

class Golden_Retriever_Dog extends Dog {
    public $ear_shape = 'floppy';

    public fetch( $thrown_thing ) {
        return 'Here is ' . $thrown_thing . '!!!';
    }
}

$max = new Golden_Retriever_Dog();
echo $max->ear_shape; // Prints "floppy"
echo $max->fetch( 'stick' ); // Prints "Here is stick!!!"

echo $max->bark(); // Prints "arf" thanks to inheritance from parent class, Dog
$patterns = $max->coat_patterns; // Uh oh! Golden_Retriever_Dogs don't have a coat_patterns property

See? the Golden_Retriever_Dog has a special property, ear_shape, that we’ve never bothered to specify for any other dog.

Max can also now do a special method: he can fetch() a stick (or anything). That’s something that no other Dog we’ve created can do, and we’d get an error if we tried it.

Max can also bark()—he is a Dog, after all, and inherited that method from the parent class.

But there’s something Max doesn’t have: the coat_patterns property that we defined for our other child class, Catahoula_Dog. Child classes don’t inherit methods or properties from their sibling classes, only from their parent class.

Hopefully those examples are clear! Now: What’s so helpful about parent classes, child classes, and class inheritance in general?

Why Class Inheritance is Useful in OO PHP

With class inheritance, we can convey more meaning, while writing less.

For us as programmers, the advantage of using class inheritance is that we can convey more meaning, while writing less.

When you write inheritance into your OO PHP code, you’re far less likely to need to repeatedly copy-and-paste the same code—and you’re making it possible for people to understand and reuse your structure far better than they would without class inheritance.

Why Class Inheritance is Important: A Commonsense Example

To see this using common sense, let’s examine two possible answers to the question, “What’s a golden retriever?”

  1. A golden retriever is a four-legged mammal, descended from the gray wolf, with social intelligence evolved from pack hunting, domesticated by humans, and kept as a house pet in contemporary societies across the world. There are lots of types of these domesticated-wolf-things, and what makes a golden retriever different from all the other ones is that it has floppy ears and golden fur and likes to fetch.
  2. A golden retriever is a dog with floppy ears and golden fur that likes to fetch.

Do you see how useful it is to be able to say “dog,” or Dog? In OO PHP, you have to write out all the properties and methods that make the Dog parent class special (if you were really coding about dogs in the context of other animals, that’d be public evolved_from_wolves = true; and so on).

Once you’ve done that once, why repeat yourself every time you want to talk about a specific type of dog? That’d be as crazy as example 1 above.

Class inheritance is what lets you not repeat yourself. Just extend Dog, and inherit everything that means—written down once in a centralized place—and then specify what exactly it is about a Golden_Retriever_Dog that’s important to your work.

The Liskov Substitution Principle

You can also be confident that each one of your child classes belongs to something, and has the full set of properties and methods that that belonging requires. In other words, anytime you need a generic Dog for something, you can always send a Golden_Retriever_Dog to do the job, and nothing will break. As simple as this sounds, it’s got an awesome-sounding Russian name: the Liskov substitution principle.

Summing up, class inheritance allows for more code reuse and makes swapping out components easier. That’s good for you right now, and for the people (whether you or others) who read and work with your code in the future.

An Example of Class Inheritance in WordPress: WP_Widget

Once you understand class inheritance, you see it pop up in code pretty often, but I do want to give you one concrete example within WordPress where you simply can’t avoid it: widgets.

The only way to create a new type of widget in WordPress is with code that looks like this:

class WPShout_Custom_Widget extends WP_Widget {}

Why is this? Consider two things:

  1. All WordPress widgets are alike in lots of ways. For example, they all appear in widget areas, and they should all be editable using the drag-and-drop “Widgets” sections of wp-admin and the Customizer.
  2. Despite these similarities, individual WordPress widgets are very different in what they do. Your particular widget could do anything from “feed in my Instagram stories” to “let people sign up for my mailing list.”

This is a perfect use case for class inheritance, and the WordPress core team knocked it out of the park by using OO PHP for the Widgets API. That was by far the best way for them to make the Widgets API behave as it needed to, because they could then:

  1. Create a parent class, WP_Widget, that handles all the properties and methods that all widgets have in common, and
  2. Require individual developers to extend WP_Widget to create their particular widgets’ unique behaviors.

All the details are all in our full course on widgets:

Creating WordPress Widgets: The Complete Guide

If you’ve understood this article and the previous one, learning the Widgets API should be—well, not a breeze (it’s still pretty musty and complicated)—but definitely something that makes general sense.

And That’s the Basics of Class Inheritance in OO PHP

Object orientation is a rich and deep field, and we’re really digging into it. I hope you now understand what topics like “inheritance” and “extending a base class” mean in software, how to write your own parent and child classes in object-oriented PHP, and how to work with class inheritance where it crops up in WordPress development. Thanks for reading!

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Separate tags by commas
To access this feature, please upgrade your account.
Start your free month
Free Preview