如何使用 php 更改 Wordpress 全局 post 标题

How to alter Wordpress global post title using php

我知道我可以使用:

global $wp_query;
$wp_query->is_page = true;

例如将全局 is_page 条件设置为真。

我能否以类似的方式更改全局 post 标题以影响 the_title() 返回值?

澄清一下:

我需要使用 "virtual page" 案例,其中实际上没有加载 post 并且我不想使用任何现有的 post 标题。只需向当前全局变量注入一些自定义标题,这样我就可以在当前页面上使用 the_title 时得到它。

要修改标题,您可以使用 wordpress 的内置钩子:

function suppress_if_blurb( $title, $id = null ) {

    if ( in_category(' blurb', $id ) ) {
        return '';
    }

    return $title;
}
add_filter( 'the_title', 'suppress_if_blurb', 10, 2 );

https://codex.wordpress.org/Plugin_API/Filter_Reference/the_title

终于找到了。很高兴它非常简单 :) 但这段代码还将为 "fake post/page":

创建所有其他 post 变量
$post_id = -99; // negative ID, to avoid clash with a valid post
$post = new stdClass();
$post->ID = $post_id;
$post->post_title = 'Some title or other';
$wp_post = new WP_Post( $post );
wp_cache_add( $post_id, $wp_post, 'posts' );
global $wp, $wp_query;
$wp_query->post = $wp_post;
$wp_query->posts = array( $wp_post );
$wp_query->queried_object = $wp_post;
$wp_query->queried_object_id = $post_id;
$wp_query->is_404=false;
$wp_query->is_page=true;
$GLOBALS['wp_query'] = $wp_query;
$wp->register_globals();

More details here!