Actions are actually hooks which are executed at specific points in code execution or on some event trigger. Filters are used to adjust a content before saving to the database or before rendering to browser.
What I wanted to do is to add a custom link to page listings, so I needed a filter to do that. As I needed to add those links only to pages and not posts or any other post type, I used a filter page_row_actions.
Basic usage of filters in WordPress is in a few steps:
- Create a PHP function to filter the content (in our case, add links)
- Hook that PHP function to a WordPress filter using add_filter method
So let’s create our PHP filter function, so add this code to your theme’s functions.php file (or the plugin if you’re making one):
function add_facebook_link($actions, $page_object)
$actions[‘facebook_link’] = ‘<a href="https://facebook.com" class="facebook_link">’ . __(‘Go to Facebook’) . ‘</a>’;
This function is receiving 2 parameters, actions, which is all the links on the page listings, and page_object which is the actual post object for the page. After that, it adds new link to the actions array and returns the new array for rendering. Simple.
Now, we can add the filter by adding this to your theme’s functions.php file:
add_filter(‘page_row_actions’, ‘add_facebook_link’, 10, 2);
It’s quite easy, first parameter is the filter we want to use, second is the name of the function, third is priority (useful to control priorities of filter functions if we have multiple functions on the same filter) and fourth is the number of parameters our filter function has.
If you add that and refresh your admin All pages screen, you should see Go To Facebook link as the last link below every page.
Remove a link
What if we want to remove a link below pages. Easy, we just unset that from our actions array:
function remove_trash_link($actions, $page_object)
add_filter(‘page_row_actions’, ‘remove_trash_link’, 10, 2);
To get a feeling of what to do with our page_object parameter, next example will add a link to search Google for current page title, useless, but just an example:
function search_google($actions, $page_object)
$actions[‘google_link’] = ‘<a href="http://google.com/search?q=’ . $page_object->post_title . ‘" class="google_link">’ . __(‘Search Google for Page Title’) . ‘</a>’;
add_filter(‘page_row_actions’, ‘search_google’, 10, 2);
There are other useful filters available:
I hope that this little tip will help you do awesome stuff with WordPress.
Did you ever use those filters? Share your experience in comments below.