10 Ways to Write Clean Code In WordPress

  • November 18, 2024
10 Ways to Write Clean Code In WordPress

WordPress is a powerful platform for building websites, but messy code can complicate project management. Writing clean code in WordPress helps keep your site running efficiently, makes updates easier, and ensures it can evolve with future requirements.

This guide provides practical tips for writing clean code in WordPress, promoting better organization, scalability, and maintainability for your projects.

Tip #1: Separate Logic from Presentation

Instead of mixing PHP with HTML, use template engines like Blade or Twig to handle display logic while PHP focuses on data manipulation. This approach makes your code easier to debug, update, and reuse.

Bad Practice: Mixing PHP logic with HTML output creates hard-to-maintain code.

<div>
    <?php
    $posts = get_posts([
      'post_type'   => 'post',
      'post_status' => 'publish',
      'posts_per_page'=> 5
    ]);
    
    foreach ($posts as $post) {
        echo '<h2>' . $post->post_title . '</h2>';
    }
    ?>
</div>
PHP

Best Practice

// PHP: Fetch data in your template file or controller
$context['posts'] = get_posts([
                      'post_type'   => 'post',
                      'post_status' => 'publish',
                      'posts_per_page'=> 5
                    ]);

// Twig: Handle display logic
{% for post in posts %}
    <h2>{{ post.post_title }}</h2>
{% endfor %}
PHP

This approach ensures a cleaner template file and improves reusability. Timber and Twig are tools that help separate logic from presentation, enabling a cleaner and more maintainable codebase.

Tip #2: Split functions.php into Several Files

Instead of packing all your functions into one large functions.php file, break them up into smaller, focused files. Each file can handle specific tasks like custom post types or widgets, making your code more organized and easier to update.

Bad Practice: A bloated functions.php file is hard to manage.

add_action('init', function () {
    register_post_type('custom_type', ['label' => 'Custom Type']);
});

// Additional unrelated code cluttered together
function my_custom_function() {
    // ...
}
PHP

Best Practice

// functions.php
require_once get_template_directory() . '/inc/post-types.php';
require_once get_template_directory() . '/inc/custom-functions.php';
PHP
/inc/post-types.php
add_action('init', function () {
    register_post_type('custom_type', ['label' => 'Custom Type']);
});
PHP

This modular approach helps isolate specific features and makes debugging easier.

Tip #3: Implement Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) can help make your WordPress code cleaner and more reusable. By organizing code into classes and objects, you can manage related functions together, making it easier to maintain and scale your projects.

This approach is especially helpful when you need to add new features or troubleshoot specific sections of your site.

Bad Practice: Procedural code can become redundant and messy.

add_action('init', 'register_custom_post_type');
function register_custom_post_type() {
    register_post_type('event', ['label' => 'Event']);
}
PHP

Best Practice

class CustomPostTypes {
    public static function init() {
        add_action('init', [__CLASS__, 'register_event_post_type']);
    }

    public static function register_event_post_type() {
        register_post_type('event', ['label' => 'Event']);
    }
}

CustomPostTypes::init();
PHP

Tip #4: Leverage Hooks Effectively

WordPress hooks, such as add_action and add_filter, allow you to modify how WordPress behaves without touching core files.

This ensures that your code is more maintainable and compatible with future updates. By leveraging hooks effectively, you can extend functionality, manage events, and interact with WordPress in a clean and structured way.

Bad Practice: Direct modifications make updates risky

$post = get_post($post_id);
$post->post_title = 'Updated Title';
wp_update_post($post);
PHP

Best Practice: Using hooks ensure compatibility across themes and plugins)

add_action('save_post', function ($post_id) {
    if (get_post_type($post_id) === 'event') {
        // Automatically set a default title for events
        $post = get_post($post_id);
        $post->post_title = 'Default Event Title';
        wp_update_post($post);
    }
});
PHP

Tip #5: Adhere to WordPress Coding Standards

Follow WordPress’s established coding standards to ensure your code is clean, consistent, and easier for others to understand. This includes proper indentation, naming conventions, and avoiding unnecessary code repetition.

Bad Practice

function MyFunction ($arg){return $arg + 1;}
PHP

Best Practice

function my_function( $arg ) {
    return $arg + 1;
}
PHP

Tip #6: Avoid Global Variables

Global variables can lead to unpredictable behavior and make your code harder to debug and maintain. Instead, aim to use function parameters, classes, or WordPress options to store and pass data.

This reduces the risk of accidental conflicts and makes your code cleaner and more modular. By limiting the use of globals, you promote better scoping and improve overall code quality.

Bad Practice

global $some_value;
$some_value = 'data';
PHP

Best Practice

class MyClass {
    private $some_value;

    public function set_value( $value ) {
        $this->some_value = $value;
    }

    public function get_value() {
        return $this->some_value;
    }
}
PHP

Tip #7: Use Namespaces

Namespaces help organize your code by grouping related functions, classes, and constants into specific, named spaces. This avoids naming conflicts, especially in larger projects or when integrating third-party libraries.

Using namespaces keeps your code clean and easy to maintain by clearly defining where each piece of functionality belongs. It also promotes better code organization and modularity, making it easier to locate and reuse components.

Bad Practice

class Utils {
    public static function debug( $data ) {
        error_log( print_r( $data, true ) );
    }

    public static function logError( $message ) {
        error_log( $message );
    }
}
PHP

Best Practice

namespace MyPlugin\Utils;

class Debug {
    public static function log( $data ) {
        error_log( print_r( $data, true ) );
    }
}

class Logger {
    public static function error( $message ) {
        error_log( $message );
    }
}
PHP

Tip #8: Minimize Database Queries

Minimizing database queries is essential for improving performance and ensuring your WordPress site runs efficiently. Each query that accesses the database adds load time, and excessive queries can significantly slow down your website.

Bad Practice

foreach ( $post_ids as $id ) {
    $post = get_post( $id );
    echo $post->post_title;
}
PHP

Best Practice

$posts = get_posts( [ 'include' => $post_ids ] );
foreach ( $posts as $post ) {
    echo $post->post_title;
}
PHP

Tip #9: Utilize Dependency Injection

Using dependency injection in your WordPress development can significantly improve code maintainability and flexibility. Instead of directly instantiating classes within your code, dependency injection allows you to pass objects or dependencies to a class from the outside.

Bad Practice

class MyService {
    public function __construct() {
        $this->mailer = new Mailer();
    }
}
PHP

Best Practice

class MyService {
    private $mailer;

    public function __construct( Mailer $mailer ) {
        $this->mailer = $mailer;
    }
}
PHP

Tip #10: Optimize Asset Loading

Efficiently manage the loading of CSS and JavaScript files by enqueuing only what is necessary for each page. Overloading assets can slow down your site and affect performance.

Bad Practice

function load_assets() {
    wp_enqueue_style( 'main-styles', get_template_directory_uri() . '/style.css' );
    wp_enqueue_script( 'main-scripts', 
               get_template_directory_uri() . '/scripts.js', [], null, true );
}
add_action( 'wp_enqueue_scripts', 'load_assets' );
PHP

Best Practice: This approach reduces unnecessary file loading, improves page speed, and enhances the user experience.

function load_assets() {
    if ( is_singular( 'post' ) ) {
        wp_enqueue_style( 'post-styles', get_template_directory_uri() . '/post.css' );
    }

    if ( is_page_template( 'custom-template.php' ) ) {
        wp_enqueue_script( 'custom-script', 
        get_template_directory_uri() . '/custom.js', [], null, true );
    }
}
add_action( 'wp_enqueue_scripts', 'load_assets' );
PHP

Conclusion

Maintaining clean code in WordPress is key for long term success. By following best practices, developers can write code that’s structured, scalable, and easy to maintain.

These habits lead to websites that are reliable, adaptable to changes, and efficient to work with. Writing cleaner code ensures better performance, easier updates, and smoother troubleshooting, setting the foundation for sustainable WordPress development.

Photo by Ilya Pavlov on Unsplash