Occasionally, you might want to prepend a custom text to posts titles of a specific category. For instance, you would like to automatically display “[Sponsored]” right before titles of your sponsored posts.
Below is the code to conditionally prepend custom text to post titles in WordPress.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//* Conditionally prepend custom text to post titles in WordPress | |
add_filter('the_title', 'customprefix_prepend_text', 10, 2); | |
function customprefix_prepend_text($title, $id) { | |
if (is_feed() && in_category('custom-category', $id)) { | |
$title = '<span class="custom-class">Custom text:</span> ' . $title; | |
} | |
return $title; | |
} |