WordPress OOP Based Plugin Development
Table of Content
Object Oriented Approach is beneficial over Procedural Approach in terms of code re-usability, providing much more organised structure to code, etc. So we will learn a basic of WordPress Object Oriented Plugin Development.
WordPress Object Oriented Plugin Development
So first of all we will start from initialising a class named WordPress.
<?php
class WordPress{
function __construct(){
}
}
new WordPress();
?>
Every class contains the “__construct” function. It is a constructor method for class based approach and “new” is used to create object of class.
<?php
class WordPress{
function __construct(){
}
function first(){
echo 'Hello World';
}
}
$obj = new WordPress();
$obj->first();
Now let’s say we have a function named “first” and we want to get its content i.e. ‘Hello World’. So we will first create an object of class by using “new” and then we will call the function named “first” like $obj->first(), and it will simply print “Hello World”.
If we want to get the contents of function “first()” in the beginning then we can simply call this function in our constructor as:
<?php
class WordPress{
function __construct(){
$this->first();
}
function first(){
}
}
$obj = new WordPress();
Now, as there are many predefined hooks in WordPress, so now a next pain we face is how to load a function when the particular hook fires. So here is the simple solution.
<?php
class WordPress{
function __construct(){
add_action( 'hook_name', array( $this, 'first' ) );
}
function first(){
echo 'Hello World';
}
}
$obj = new WordPress();
Support
Still have any issue feel free to add a ticket and let us know your views to make the code better https://webkul.uvdesk.com/en/customer/create-ticket/
Thanks for Your Time! Have a Good Day!