Filter hooks let you change data before WordPress uses it. They help you customize how WordPress works without changing core files.
0
0
Common filter hooks in Wordpress
Introduction
You want to change the text of a post title before it shows on your site.
You need to modify the content of a post before it appears to visitors.
You want to add extra HTML or text to the end of every post automatically.
You want to change the URL of an image before it loads.
You want to adjust the way WordPress formats dates or times.
Syntax
Wordpress
add_filter('hook_name', 'your_function_name', priority, accepted_args); function your_function_name($value) { // modify $value return $value; }
add_filter connects your function to a filter hook.
Your function must return the modified value for WordPress to use it.
Examples
This adds 'Hello: ' before every post title.
Wordpress
add_filter('the_title', 'change_title'); function change_title($title) { return 'Hello: ' . $title; }
This adds a thank you message at the end of every post content.
Wordpress
add_filter('the_content', 'add_footer_text'); function add_footer_text($content) { return $content . '<p>Thank you for reading!</p>'; }
This changes the upload folder to a custom folder.
Wordpress
add_filter('upload_dir', 'custom_upload_dir'); function custom_upload_dir($dirs) { $dirs['subdir'] = '/custom_folder'; $dirs['path'] = $dirs['basedir'] . $dirs['subdir']; $dirs['url'] = $dirs['baseurl'] . $dirs['subdir']; return $dirs; }
Sample Program
This code adds 'Prefix: ' before every post title using the 'the_title' filter hook. It shows how the title changes when the filter runs.
Wordpress
<?php // Add prefix to all post titles add_filter('the_title', 'add_prefix_to_title'); function add_prefix_to_title($title) { return 'Prefix: ' . $title; } // Usage example: simulate getting a title $original_title = 'My First Post'; $filtered_title = apply_filters('the_title', $original_title); echo $filtered_title; ?>
OutputSuccess
Important Notes
Always return the modified value in your filter function.
Use the right hook name to target the data you want to change.
You can set priority to control the order if multiple filters use the same hook.
Summary
Filter hooks let you change WordPress data before it is used or shown.
Use add_filter to connect your function to a filter hook.
Your function must return the changed data for WordPress to use it.