skip to Main Content

I have an page (with snippet code and short code and manual php code) and it call a REST API and base Of response, I want change tag title of this page (Not in database).and it was change every call.

i try do :

in snippet code:

$GLOBALS['MyTitle'] = $response-> title;

in function:

function change_title($title) {
 
        $variable = $GLOBALS['MyTitle'];
      
        if (!empty($variable)) 
        {
             $title = $variable;
        } 
    
    return $title;
}
add_filter('pre_get_document_title', 'change_title',500);

but it was empty every time because the function section run sooner then snippet code(Api Call).

WordPress has not any function for change title tag text? like wp_set_title('my title') to use without add_filter?

2

Answers


  1. Changing title of the page dynamically by applying the filter the hook used for the filter is document_title_parts. Here is the official wordpress documentation link and below is the example. In this example i have used get method for API.

    add_filter( 'document_title_parts', 'function_to_dynamic_title');
    function function_to_dynamic_title( $title_parts_array ) {
    
            $request = wp_remote_get( 'https://dummyjson.com/products/1' );
    
            if( is_wp_error( $request ) ) {
                return $data;
            }
    
            $body = wp_remote_retrieve_body( $request );
    
            $data = json_decode( $body );
    
            $title_parts_array['title'] = $data->title;
        
        return $title_parts_array;
    }
    

    Screenshot for your reference
    enter image description here

    Login or Signup to reply.
  2. In WordPress, we have an action to change the title programmatically.

    add_filter('the_title','your_callback_function');
    function your_callback_function($data)
    {
      global $post;
      // add your condition according to page 
      return 'Desired Title'. $post->ID;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search