How to Object Oriented Programming in WordPress using Control Structures

Editor's note (2026): We've rewritten this 2014 post for clarity, fixed the code examples (the original used curly quotes that PHP can't run and mislabeled a switch statement as a loop), and added a short object-oriented WordPress example.

Before you write object-oriented code for WordPress, you need a solid grasp of control structures: the parts of a program that decide which code runs and how many times.

There are two main kinds:

  • Conditional structures: if/else and switch
  • Loops: while, do...while, for, and foreach

Conditionals

if / else

An if statement reads almost like plain English: if this is true, do one thing; otherwise, do something else.

<?php
if ( $condition ) {
    // Do one thing
} else {
    // Do something else
}

switch

A switch statement compares one value against several possible cases. Each case ends with break so PHP doesn't fall through to the next one.

<?php
$persons_name  = 'Tom';
$email_address = '';

switch ( strtolower( $persons_name ) ) {
    case 'tom':
        $email_address = 'tom@example.com';
        break;
    case 'david':
        $email_address = 'david@example.com';
        break;
    default:
        $email_address = null;
        break;
}

Loops

Loops repeat code and control how many times it runs.

  • while checks the condition first and repeats while it's true.
  • do...while runs the code once, then checks the condition at the end.
  • for is handy for counting through a range of numbers.
  • foreach goes through each item in an array, the loop you'll use most in WordPress.
<?php
$posts = get_posts( [ 'numberposts' => 5 ] );

foreach ( $posts as $post ) {
    echo esc_html( get_the_title( $post ) ) . '<br>';
}

Putting it together: object-oriented WordPress

Object-oriented programming (OOP) organizes code into classes, which makes plugins modular, reusable, and easier to maintain. Control structures live inside a class's methods:

<?php
class My_Notice_Plugin {

    public function __construct() {
        add_action( 'admin_notices', [ $this, 'show_notice' ] );
    }

    public function show_notice() {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        echo '<div class="notice notice-info"><p>Welcome back, administrator!</p></div>';
    }
}

new My_Notice_Plugin();

Here the class registers a WordPress hook, and the if statement controls who sees the notice. Master conditionals and loops first, and object-oriented WordPress development becomes much easier.


Need custom WordPress development? I.T. For Less can help — contact us.

I.T. Support