Recently we had to build a wordpress plugin. The requirements were that two buttons would be assigned to every post about the featured image. Instead of hacking into the existing theme, we opted to use the wordpress action hook “the_post” to achieve our goals.
The Dilemma
The thing to note here, is that the theme was very custom. The owners of the site were themselves developers, and confused about how to edit the theme. In actuality, the pages were constructed via functions in several php files.
The posts, like many custom themes, had various layouts which each had their own functions. The requirement was that each of these variants as well as the pages themselves, must have the buttons available to them.
The Solution
We could have approach things brute force, by finding the function generating the posts. We could then include a line calling our function which generated the buttons. This would have taken a long time since the theme was quite detailed.
We opted for the wordpress action hook options. In particular, the little documented “the_post“. So by using the following syntax
[php]
add_action( ‘the_post’, ‘wob_buttons’ );
[/php]
we were able to have our function, run everytime a post was generated. Thing is, this also ran on the home page load. We needed a way to force this to happen only during the loop. To do this, we ended up on a syntax like the following
[php]
function xyz_buttons(){
global $post;
if(in_the_loop()){
[/php]
The “in_the_loop” function is a perfect tool for verifying that you are within a post loop when your function is executed.
The Conclusion on WordPress Post Hooks
This is by far the best way to alter a theme via plugin. Often time, regardless of the complexity of the theme, these hooks still work quite well for your needs. Action hooks are often easier in our opinion since they are dependable. Filters are an alternative to hooks but you cannot guarantee that those particular functions will be called.
El dilema
La solución
add_action( ‘the_post’, ‘wob_buttons’ );
[/php]
function xyz_buttons(){
global $post;
if(in_the_loop()){
[/php]