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.
applying few changes we can turn this into Wordpress OOP function. First we create a class in functions.php as follows:
Then we create a class constructor inside the class, as follows:
The we copy the theme_setup() function inside the class after the constructor, however we add the key word public.
After that we write the action inside the constructor as follows:
Finally we just initiate the class using the new keyword, as follows:
That's it for today, if you have any questions, pop them and I'll get back to you.
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.
Good luck 😊
ReplyDelete