Is using WordPress filters hard?
Not really. Just need to understand the concepts. Its a good idea to learn PHP and how programming languages work.
If you like to tinker with template files like me you’ll be messing with and editing files. However, its time consuming and with each update the need to dig through documentation is a hassle.
Using WordPress filters offers an option to change some of the default output behavior without editing any template file.
You can read a couple good posts on better understanding Child Theme Action Hooks and Using WordPress Filters on ThemeShaper.
How to better understand WordPress filters?
In order to better understand filters, know that filters allow you to change the default behavior of functions already included in WordPress.
Example is grabbing the post thumbnail, one of many stock WordPress functions. In this instance, you’d want to add a new attribute inside the default img tag output.
The default WP output for getting the function the_post_thumbnail() is:
<img src="ImageSource" class="SomeClass" alt+"SomeAltText" title="SomeTitle" />
To add an itemprop attribute to the img tag, you can use a filter to change the ouput to:
<img itemprop="MyNewProperty" class="SomeClass" alt+"SomeAltText" title="SomeTitle" />
Given the power of using Schema.org’s microdata format, it is important for SEO to add structured data. It’s fodder for search engines and its the future to writing elegant code with meaningful meta data.
Solution changing WordPress default function output
If you understand how to use action hooks and how to use a filter, then your on the way to becoming a better WordPress developer.
For the example above to change, the action hook we like to filter is the post_thumbnail_html.
To better understand, you can check out an article about how to strip inline image width and height attributes – the opposite of what we’re going for here.
In the end, my solution is the following simple lines to change the default the_post_thumbnail() output to include the new itemprop attribute.
In the functions.php file, you just need to add these lines to accomplish the new output.
function add_itemprop( $html ) {
$html = str_replace('<img','<img itemprop="photo"',$html);
return $html;
}
add_filter( 'post_thumbnail_html', 'add_itemprop' );