求助:如何修改WordPress的the_title()仅替换指定文本并保留订单号
Got it, let's work through this solution. You want to tweak the output of the_title() so that only the word 'ORDER' gets swapped to 'QUOTE'—leaving order numbers like #3344 untouched—and avoid modifying every title on your site. Here are two reliable approaches:
1. Use a WordPress Filter (Global, Conditional)
This method uses the the_title filter hook to intercept title outputs site-wide, but only applies the replacement when your condition is met. Add this to your theme's functions.php file (or a custom plugin):
add_filter( 'the_title', 'swap_order_to_quote_in_titles', 10, 2 ); function swap_order_to_quote_in_titles( $title, $post_id ) { // First, check if the title actually contains 'ORDER' (to avoid unnecessary processing) if ( str_contains( $title, 'ORDER' ) ) { // Replace only the exact word 'ORDER' with 'QUOTE'—order numbers stay intact return str_replace( 'ORDER', 'QUOTE', $title ); } // Return the original title if no 'ORDER' is found return $title; }
Refine the Condition (Optional)
If you need to limit this to specific pages/posts (e.g., only the "Order Details" page, or a custom post type), adjust the condition:
- Target a specific page ID:
if ( $post_id === 123 && str_contains( $title, 'ORDER' ) ) { // Replacement logic here return str_replace( 'ORDER', 'QUOTE', $title ); } - Target a custom post type:
$post_type = get_post_type( $post_id ); if ( $post_type === 'customer_order' && str_contains( $title, 'ORDER' ) ) { // Replacement logic here return str_replace( 'ORDER', 'QUOTE', $title ); }
2. Modify the Template Directly (Localized)
If you only need the change on one specific template (e.g., page-order-details.php), skip the filter and adjust the the_title() call directly:
<?php $page_title = get_the_title(); // Check if the title has 'ORDER' before modifying if ( str_contains( $page_title, 'ORDER' ) ) { echo str_replace( 'ORDER', 'QUOTE', $page_title ); } else { // Fall back to the default title output the_title(); } ?>
Notes for Compatibility
- If your server runs PHP older than 8.0, replace
str_contains( $title, 'ORDER' )withstrpos( $title, 'ORDER' ) !== false(it does the same check, just for older PHP versions). - To make the replacement case-insensitive (e.g., replace 'Order' or 'order' too), use
str_ireplace()instead ofstr_replace().
内容的提问来源于stack exchange,提问作者Peter John Goodwin

