mondi
mondi

Reputation: 559

How to alter Wordpress global post title using php

I know i can use:

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

For example to set the global is_page conditional to true.

Can i change the global post title in a similar way so it would effect the the_title() returned value?

To clarify things:

I need for a use of a "virtual page" case, where no post is actually loaded and i don't want to use any existing post title. just inject some custom title to the current globals so i will get it when using the_title on the current page.

Upvotes: 1

Views: 1873

Answers (2)

mondi
mondi

Reputation: 559

Finally found it. gladly it's very simple :) but this piece of code will also create all other post vars for a "fake post/page":

$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!

Upvotes: 0

enno.void
enno.void

Reputation: 6579

To modify the title you can use a build in hook of 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

Upvotes: 1

Related Questions