未加星标

Simplifying WordPress's functions.php with OOP

字体大小 | |
[开发(php) 所属分类 开发(php) | 发布者 店小二03 | 时间 2018 | 作者 红领巾 ] 0人收藏点击收藏

I love WordPress, and I use it for most of my clients' sites. Between its built-in features, rich plugin ecosystem and endless learning resources/documentation, I can spend more time building features unique to each project and less time reinventing the wheel.

That being said, WordPress isn't perfect. Likephp itself, the WordPress API often feels clunky and inconsistent. I spend lots of time Googling functions and action hooks that I frequently use because I can't remember their names. This part of WordPress is less than ideal.

When I learned Laravel, I discovered how much better coding could feel when using a simple and elegant object-oriented API. That feeling was like a drug: once I had a taste I was hooked. I wanted to lace my WordPress development with a little bit of that sweet object-oriented programming (OOP for short).

Enter functions.php .

I maintain my own Underscores -based starter theme that I use for most of my projects, and its functions.php felt clunky. My functions file was fairly typical and close to the stock Underscores functions.php . Here's a rundown of what it was doing:

Inside the after_setup_theme hook: Add theme support for title-tag , custom-logo , post-thumbnails , customize-selective-refresh-widgets and an array of html5 components using add_theme_support() . Register navigation menus using register_nav_menus() . Add image size using add_image_size() . Inside the wp_enqueue_scripts hook: Enqueue styles and scripts with their respective wp_enqueue_style() and wp_enqueue_script() functions. Include related files.

Again, this is a fairly typical functions.php , and there's nothing wrong with it. However, I have a few issues with how it's setup:

Memorization isn't my biggest strength, and remembering which functions start with the word add , register and wp_enqueue just isn't going to happen for me. Action hooks fail silently, and I can't tell you how many times I've typed after_theme_setup instead of after_setup_theme . I literally add theme support for the exact same things in every project, and I don't really want that identical boiler plate cluttering my functions.php code.

Let's take a step back and consider what the functions.php code is actually doing here.

When you think about it, everything that's happening is performing some kind of action on the theme itself. What if we had a theme object that we could perform these actions on with a simple, object-oriented API?

A Simple, Object-Oriented API

I don't want to remember which functions start with the word add , register or wp_enqueue . In fact, all of these essentially do the same thing: they add something to the theme. So I'm going to use the word add for all of these. I want to add theme support, add nav menus, add image sizes, and add scripts.

I'm lazy. Fight me.

I want my functions.php to look more or less like this:

<?php // functions.php require get_template_directory() . '/classes/theme-class.php'; $theme = new MyTheme; $theme->addNavMenus([ 'menu-1' => 'Primary', ]); $theme->addSupport('post-thumbnails'); $theme->addImageSize('full-width', 1600); $theme->addStyle('theme-styles', get_stylesheet_uri()) ->addScript('theme-script', get_template_directory_uri() . '/js/custom.js');

No more memorizing hook names and function prefixes. Rejoice!

It is also abundantly clear that all of these methods are performing an action on the theme itself.

So let's build this.

We'll start by defining a theme class in a new file and building a addNavMenus() method. Essentially, we're just building wrappers around the existing WordPress hooks and functions, so this shouldn't be too complicated.

<?php // theme-class.php class MyTheme { public function addNavMenus($locations = array()) { add_action('after_setup_theme',function() use ($locations){ register_nav_menus($locations); }); } }

Let's unpack what's going on here.

We define our class MyTheme , make a public method for addNavMenus() and give it the same arguments as the register_nav_menus() WordPress function.

Inside the method, we add an action to the after_setup_theme hook, and create a closure (PHP's flavor of an anonymous function) where we call the WordPress register_nav_menu() function. The $locations variable is passed into the closure using PHP's use keyword, otherwise the variable would be outside of the closure's scope.

Side note: closures are supported as of PHP 5.3, and they are how I interact with WordPress hooks 90% of the time to avoid cluttering up the global namespace. However, despite WordPress's adoption of modern technologies like React.js, WordPress officially maintains its PHP backwards compatibility to PHP 5.2, which reached its end-of-life in January 2011 ♂

Reduce Hook Failures

In the addNavMenus() method, we've solved the first problem we defined above: we've simplified the API (no more remembering prefixes like register ). We still have our second problem though: misspelled hooks fail silently. As I build out my theme class's methods, at some point I'm probably going to write after_theme_setup instead of after_setup_theme somewhere and not notice.

Let's fix that by creating a private method that fires the after_setup_theme action hook, then calling that method within the addNavMenus() method instead of the add_action() function.

<?php // theme-class.php class MyTheme { private function actionAfterSetup($function) { add_action('after_setup_theme', function() use ($function) { $function(); }); } public function addNavMenus($locations = array()) { $this->actionAfterSetup(function() use ($locations){ register_nav_menus($locations); }); } }

So this is kind of cool: we're passing in the closure within addNavMenus() to our actionAfterSetup() method, then passing it to the closure via the use keyword, then calling the code from its variable name from within the closure. Wonderful witchcraft!

...if that description didn't make sense at all, just study the code and it isn't too bad.

I've prefixed the method with the word "action" to tell me this is an action hook, and I've made it private because thi

本文开发(php)相关术语:php代码审计工具 php开发工程师 移动开发者大会 移动互联网开发 web开发工程师 软件开发流程 软件开发工程师

分页:12
转载请注明
本文标题:Simplifying WordPress's functions.php with OOP
本站链接:https://www.codesec.net/view/620842.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 开发(php) | 评论(0) | 阅读(10)