In case some of you don't know what the title of this post means, it has to do with building plugin for WordPress. Let me explain a little on what does an action means in WordPress. Basically, we can add a function to an action or event (whatever you called it) in WordPress to perform some task before or after the action or event has occured.
Problem
The reason why i bought this post up was because i nearly get frustrated working on my WordPress plugin because there wasn't any action listed in WordPress plugin API that stated an action that can be attached to an event before or after an excerpt is being bought out! Search all over the place, fail. So i decided to do a trial and guess with these action thing for my plugin to attached an event when an excerpt is being bought out.
Solution
In case you might not aware how a excerpt is being printed out on the template, they used
the_excerpt();
This will print out the excerpt in your WordPress. So i tried using the_excerpt to be placed into my WordPress add_action statement as shown below,
add_action('the_excerpt', 'hpt_attach_excerpt');
'hpt_attach_excerpt' is the function call when excerpt is being triggered. To my surprise, it work! But it will only display whatever the function, 'hpt_attach_excerpt' contains as shown below.
So where is my regular excerpt? It seems like if i attached a defined action used in WordPress that are not listed in the WordPress Plugin API, it will be overwritten by my own method 'hpt_attach_excerpt'. I digged again to find the method in WordPress site that will provide me with the missing excerpt i was looking for. Fail. So i digged into the source code of WordPress and managed to find the key method that return the excerpt of a post, get_the_excerpt(). get_the_excerpt() is the based method that retrieve the data from the database to the_excerpt for it to filter. Now i write the code as follow,
function hpt_attach_excerpt() { echo "This is the function 'hpt_attach_excerpt' produce"; echo get_the_excerpt(); } add_action('the_excerpt', 'hpt_attach_excerpt');
Looking back to the display to check whether the attachment has completed.
There it is! Both my function message and my excerpt message!
P.S: You can use add_filter if you do not wish to overwrite the default function of 'the_excerpt' function.
Conclusion
If you have read through the post, you might aware that this is not only restricted to adding action for excerpt. This shows that we can add any WordPress function that are not defined in WordPress Plugin API (Offical action available) as action and rewrite or append any type of instruction to the default action given by WordPress. Can't find your action needed to perform your WordPress plugin? You just found the answer! Hope this can help many developers who are working on their plugin! ( Thanks for all the wonderful plugin developed! )
One thought on “Tutorial: How to add action to excerpt in WordPress”
Comments are closed.