0

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
  • Does this answer your question? wordpress.stackexchange.com/questions/33101/… Commented Feb 7, 2023 at 8:37
  • @laraCoder no, I saw it later. most of them add a predefine text to title. and global variable not work for my end Commented Feb 7, 2023 at 9:29

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

6 Comments

thank you @j-shabu but I told in my question. i not want use $post I call an api and the param of it must show as title.
@foadabdollahi I have updated the answer please check it.
'YOUR TEXT DYNAMIC #' is an static text :)
Can you send me the api url ?
the api is in local sever and has not public view but it is not difference use mockapi.io and call it in an snippet and shortcut it in a page . then change page title base of api result
|
0

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;
}

1 Comment

not work with my global parameter defined in snippet code(call external API)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.