Site icon Hip-Hop Website Design and Development

How to change page title (from a plugin) in twentytwentyone theme

First, is it even possible to change the page title from a plugin (specifically, from a shortcode defined in a plugin)? This answer says no, but there are certainly reasonable use cases for it. Like, say, my use case (the shortcode displays detail page content for an item of a collection … so, I put the shortcode on a page; what’s the page title supposed to be? It depends on the detail item.).

I have tried every method I can find:

$_SESSION['custom_page_title'] = $eventData['eventtitle'];


//attempt 1
add_filter('document_title_parts', 'my_custom_title');
function my_custom_title( $title ) {
  // $title is an array of title parts, including one called `title`

  $title['title'] = stripslashes($_SESSION['custom_page_title']);

  return $title;
}


//attempt 2
add_filter("pre_get_document_title", "my_callback");
function my_callback($old_title){
    return stripslashes($_SESSION['custom_page_title']);
}


//attempt 3
add_filter('the_title','some_callback');
function some_callback($data){
    return stripslashes($_SESSION['custom_page_title']);

}


//attempt 4
add_filter( 'wp_title', 'custom_titles', 10, 2 );
function custom_titles( $title, $sep ) {

    //Check if custom titles are enabled from your option framework
    if ( ot_get_option( 'enable_custom_titles' ) === 'on' ||  (1 == 1)) {
        $title = stripslashes($_SESSION['custom_page_title']);
    }

    return $title;
}

But none of them work (with default twentytwentyone theme).

The plugin is a custom one made by me. The use case is simply to change the page title, based on data that the plugin knows. It’s pretty simple in concept. Not really another way to do it.

The shortcode defined in the plugin is displaying the detail for one specific entity (something like /individual_display?id=5 ) and the page should be titled accordingly. The page shouldn’t be titled "Individual Display" or whatever, it should be titled "Actual Name of The Individual Thing That Happens to Have ID #5"

Is it possible, and if so, how?