Skip to content

Instantly share code, notes, and snippets.

@shirayukikitsune
Last active February 28, 2018 18:43
Show Gist options
  • Save shirayukikitsune/be9c8dc4fdba1407d9231412c589cc79 to your computer and use it in GitHub Desktop.
Save shirayukikitsune/be9c8dc4fdba1407d9231412c589cc79 to your computer and use it in GitHub Desktop.
A PHP abstract class that will automatically register all methods as a wordpress action or filter
<?php
/**
* When a class extends this, this will use PHP reflection to automatically register actions and filters
* Note that this class cannot be instantiated, it is marked as abstract
*
* In order to add a method as a filter, simply name it as `filter_FILTERNAME`. For example: `filter_body_class` will add that method as a hook for the filter 'body class'
* The same applies to actions, but the naming changes to `action_ACTIONNAME`. For example: `action_widgets_init`
*/
abstract class Autohook {
public function __construct() {
$class = static::class;
$reflection = new \ReflectionClass($class);
$methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
foreach ($methods as $method) {
if (strncmp($method->name, "action_", 7) === 0) {
\add_action(substr($method->name, 7), [$this, $method->name]);
} elseif (strncmp($method->name, "filter_", 7) === 0) {
\add_filter(substr($method->name, 7), [$this, $method->name]);
}
}
}
}
<?php
class ThemeBootstrap extends Autohook {
/**
* Method called when theme is ready
*/
public function action_after_setup_theme() {
// You can add the after_setup_theme code here, for example:
add_theme_support('title-tag');
add_theme_support('post-thumbnails');
add_theme_support('custom-logo');
add_theme_support('custom-background');
register_nav_menus([
'primary' => 'Primary Menu',
]);
add_theme_support( 'html5', [
'search-form',
'comment-form',
'comment-list',
'gallery',
'caption'
]);
add_theme_support( 'post-formats', [
'aside',
'image',
'video',
'quote',
'link'
]);
}
/**
* Method called when scripts and styles need to be enqueued
*/
public function action_wp_enqueue_scripts() {
// Enqueue google fonts
wp_enqueue_style('google-fonts', 'https://fonts.googleapis.com/css?family=Fira+Sans|Roboto+Slab:700');
// This style already includes bootstrap
wp_enqueue_style('theme-style', get_stylesheet_uri(), ['google-fonts']);
}
public function action_widgets_init() {
register_sidebar([
'name' => 'Footer',
'id' => 'footer',
'description' => '',
'before_widget' => '<aside id="%1$s" class="col-12 %2$s">',
'after_widget' => '</aside>',
'before_title' => '<h2 class="widget-title">',
'after_title' => '</h2>'
]);
}
public function filter_body_class() {
// Example code from https://codex.wordpress.org/Plugin_API/Filter_Reference/body_class
$id = get_current_blog_id();
$slug = strtolower(str_replace(' ', '-', trim(get_bloginfo('name'))));
$classes[] = $slug;
$classes[] = 'site-id-'.$id;
return $classes;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment