Wordpress Plugin Tutorial Part III - Defining the Plugin Class

In order to have a good structure and to avoid collisions with other plugins, it is a good practice to wrap our plugin functionality in a PHP class. In order to do so change the "custom-comment-message.php" file to look like the following.
<?php
/* 
Plugin Name: Custom Comment Message
*/

//If the class does not exist
if (!class_exists("CustomCommentMessage")) {
    //Define the class
    class CustomCommentMessage {
        //Define the constructor
        public function __construct()
        {
            echo "<h1>Did Wordpress Run Me?</h1>";
        }
    }
}

//If the class exists
if (class_exists("CustomCommentMessage")) {
    //Create a new object of that class
    $ccmessage = new CustomCommentMessage();
}

?> 


You can understand what the code does by reading the comments. Once an object of the class "CustomCommentMessage" is created using the "new" keyword, the "__construct" function will run, which will echo the question "Did wordpress run me?". So if you navigate to the home page of your blog, you will see that the output is the same as what we saw in part two of the tutorial series.

No comments:

Post a Comment