You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何修改WordPress的the_title()仅替换指定文本并保留订单号

Replace 'ORDER' with 'QUOTE' in WordPress Page Titles (Preserving Order Numbers)

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' ) with strpos( $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 of str_replace().

内容的提问来源于stack exchange,提问作者Peter John Goodwin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 07:59:12