Both add_filter and apply_filters are functions that let us make changes to a themes or templates without editing the file. Below are few example :
Filterable for any text
Sometime in our theme, we have a string of text like ‘Feature’, ‘Best Selling’ or ‘Related activity’ that we want able to change without edit the template.
echo apply_filters('prefix_feature_text', 'Feature');
Users just need to add this to child theme function to change it
function prefix_myfeature_text() {
return 'My Custom feature Text';
}
add_filter('prefix_feature_text','prefix_myfeature_text');
Now the ‘Feature’ text will change to ‘My Custom feature Text’.
Filterable for change content to excerpt
echo apply_filters('prefix_the_content',get_the_content());
if we want to change the full post content to excerpt post only, we can add this to our child theme functions.php
function prefix_edit_content() {
return get_the_excerpt();
}
add_filter('prefix_the_content','prefix_edit_content');
now any code that wrapped with apply_filters(‘prefix_the_content’,FUNCTIONS) will change to excerpt text rather than full content.
code that use echo the_content(); will not be affected.
Filterable for featured image thumbnails
instead of using the default the_post_thumbnail(‘thumbnail’), we could try use this
$thumb = get_post_thumbnail_id( $post->ID ), 'thumbnail');
$thumb = apply_filters('prefix_my_thumb',$thumb);
echo $thumb;
so when we want to change ‘thumbnail’ to ‘medium’ in child theme, we can add this code to child theme functions
function prefix_edit_thumbnail() {
global $post;
return get_post_thumbnail_id( $post->ID ), 'medium');
}
add_filter('prefix_my_thumb','prefix_edit_thumbnail');
Now all the effected the_post_thumbnail() will change from using ‘thumbnail’ to ‘medium’ for their featured images.
No comments:
Post a Comment