Saturday, February 4, 2017

Object-Oriented Programming in WordPress - Simple Tip

Hi there,
Many developers struggle to develop themes using Object Oriented Programming techniques. Well here is a simple tip that might ease your struggle.

This is the traditional way to write a function in functions.php file.

 function theme_setup() {
  load_theme_textdomain( 'textdomain' );

  // Add default posts and comments RSS feed links to head.
  add_theme_support( 'automatic-feed-links' );
 }
 add_action( 'after_setup_theme', 'theme_setup' );



applying few changes we can turn this into Wordpress OOP function. First we create a class in functions.php as follows:

if ( ! class_exists( 'My_Functions' ) ) :
class My_Functions {
}
endif;


Then we create a class constructor inside the class, as follows:

if ( ! class_exists( 'My_Functions' ) ) :
class My_Functions {
 /**
  * Class constructor
  *
  */
 public function __construct(){
 }
}
endif;


The we copy the theme_setup() function inside the class after the constructor, however we add the key word public.

 public function theme_setup() {
  load_theme_textdomain( 'textdomain' );

  // Add default posts and comments RSS feed links to head.
  add_theme_support( 'automatic-feed-links' );
 }


After that we write the action inside the constructor as follows:

if ( ! class_exists( 'My_Functions' ) ) :
class My_Functions {
 /**
  * Class constructor
  *
  */
 public function __construct(){
  add_action( 'after_setup_theme', [$this, 'theme_setup'] );
 }
 public function theme_setup() {
  load_theme_textdomain( 'textdomain' );

  // Add default posts and comments RSS feed links to head.
  add_theme_support( 'automatic-feed-links' );
 }
}
endif;


Finally we just initiate the class using the new keyword, as follows:

new My_Functions;

Here are two videos on this topic:



That's it for today, if you have any questions, pop them and I'll get back to you.

1 comment:

Hi there, you are welcome to share your comments here!

Search The Web