At our WordPress Developers meetup on Feb 4, 2015, I did a presentation (including some live coding) about using WordPress hooks. I can’t stress enough how important I feel these are for WordPress theme developers to know how to use. There are so many different ways to do things in WordPress and hooks are definitely not a beginner technique. But once hooks are mastered, a whole new level of coding with WordPress is open to you. If you can grok hooks and use them correctly, not only will your code become more efficient, it will become more elegant. And code is poetry after all…
Slides from my talk are embedded below. They can also be accessed here if the embed is not working in your browser. I’ve also included the code examples we wrote during the session to better understand how hooks are utilized.
PHP Hook Examples
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
<?php /* * Action hook to enqueue parent theme's style.css */ add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' ); function theme_enqueue_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); } /* * Filter hook to replace "Hello" in titles with "AARRRGH" */ function cats_piratize_title($title, $id) { return str_replace('Hello', 'AARRRGH', $title); } add_filter('the_title', 'cats_piratize_title', 10, 2); /* * Filter hook to replace "Hello" in titles with "AARRRGH" (version 2) * * This version doesn't bother to accept the 2nd argument $id * It still works, but has no access to that field as a result */ function cats_piratize_title2($title) { return str_replace('Hello', 'AARRRGH', $title); } add_filter('the_title', 'cats_piratize_title2'); /* * Filter hook to add Facebook link to end of each post's content */ function cats_add_fb_link($content) { $content .= "<div><a href='#'>Check out our Facebook page, Matey!</a></div>"; return $content; } add_filter('the_content', 'cats_add_fb_link'); /* * Action hook to alter query parameters before the query is run * * NOTE: This seems like it should be a filter hook because you * are altering the $query arguments, but it's actually an action hook * and it passes the $query object by reference so that changes made * within the function below are saved without needing to return any * values from the function. */ function cats_filter_posts( $query ) { if ( !is_admin() && is_main_query()) { if ( is_home()) { //On home page, show only 'cats' posts $query->set('category_name', 'cats'); //Show *all* the 'cats' posts $query->set('posts_per_page', -1); } } } add_action('pre_get_posts', 'cats_filter_posts'); ?> |
What do you think?