如何在WordPress中在文章标题前添加额外文本(不修改原标题)
Hey there! Let's figure out how to add that extra text before your post titles without altering the original title content. First, let's look at your existing code snippet:
the_title( '<h4 class="entry-title" ' . muvipro_itemprop_schema( 'name' ) . '>', '</h4>' );
There are two straightforward ways to achieve this—one by modifying your existing template code directly, and another using a WordPress filter for more flexibility.
Method 1: Modify the the_title() Call Directly
The the_title() function accepts three parameters: the text to add before the title, the text to add after, and a boolean for whether to return the value instead of echoing it. Since you're already using the first parameter to output the opening <h4> tag, you can simply append your extra text to that parameter right before the title starts.
For example, if you want to add "Featured: " before the title, your code would become:
the_title( '<h4 class="entry-title" ' . muvipro_itemprop_schema( 'name' ) . '><span class="extra-title-text">Featured: </span>', '</h4>' );
- Wrapping the extra text in a
<span>with a class lets you style it easily with CSS later. - Make sure to include a space after your extra text so it doesn't run directly into the original title.
Method 2: Use the the_title Filter (More Flexible)
If you want to apply this change across multiple templates, or conditionally add different text based on post type/category, using the the_title filter is a better approach. This way, you don't have to edit every instance of the_title() in your theme.
Add this code to your theme's functions.php file (or a custom plugin):
add_filter( 'the_title', 'prefix_add_extra_text_before_title', 10, 2 ); function prefix_add_extra_text_before_title( $title, $post_id ) { // Skip admin area to avoid messing with backend title displays if ( is_admin() ) { return $title; } // Add conditions here if you want to target specific pages/post types // Example: Only add text on single posts and archive pages if ( is_singular( 'post' ) || is_archive() ) { $extra_text = 'Featured: '; return $extra_text . $title; } // Return original title if conditions aren't met return $title; }
Notes for the Filter Method:
- Adjust the
$extra_textvalue to whatever text you want to add. - Modify the conditional checks (
is_singular(),is_archive(), etc.) to target the specific areas where you want the extra text to appear. - The
10inadd_filter()is the priority (lower numbers run earlier), and2means the function accepts two parameters ($titleand$post_id).
Both methods will keep your original post title intact while adding the extra text you need. Pick the one that fits your workflow best!
内容的提问来源于stack exchange,提问作者Jorday

