WP Ref

Using the_title Filter to Change Post Titles When Displayed

A useful filter WordPress provides is the_title. This filter allows you to edit the title, most often used before it is displayed.

Here’s an example to see it in action. Let’s say you want to add “(New!)” to the title of your latest posts when they’re displayed. To do this, you can use the the_title filter like so:

add_filter( 'the_title', 'mp_maybe_add_new_title_prefix', 10, 2 ); function mp_maybe_add_new_title_prefix( $title, $post_id ) { $post = get_post( $post_id ); $current_dt = current_datetime(); $week_ago_today_dt = $current_dt->sub( new DateInterval( 'P10D' ) ); $post_date_dt = get_post_datetime( $post_id ); if ( $post_date_dt >= $week_ago_today_dt ) { $title = '(New!) ' . $title; } return $title; }
Code language: PHP (php)

In Conclusion

The the_title filter can allow you to make edits to the display of the title without changing the post_title data of the post itself.





Need WordPress development services?


Leave a Reply

Your email address will not be published. Required fields are marked *