Nolan Ritchie
Nolan Ritchie

Reputation: 63

how do I set the page title for a template wordpress page?

I'm fairly new to wp. I have found other people using this filter code at the top of the template to set the title for that page:

function assignPageTitle(){
  return "Custome Title";
}
add_filter('wp_title', 'assignPageTitle');

But I need to pass my assignPageTitle function 1 parameter from the query_vars $wp_query->query_vars['claim_id'], And my getTitle function builds the title based on the id of the content. Something like this i thought, but it does not work. $wp_query->query_vars['claim_id'] is null when called inside this function:

function assignPageTitle(){
  return getTitle($wp_query->query_vars['claim_id']);
}
add_filter('wp_title', 'assignPageTitle'); 

I see some people using parameters with these filters something like this:

function assignPageTitle($claim_id){
  return getTitle($claim_id);
}
add_filter('wp_title', 'assignPageTitle',10,1); 

But this is where I am getting extremely confused. WHERE is it that I can pass the claim_id variable to assignPageTitle($claim_id) function? Putting assignPageTitle(312) under that filter code does nothing, and wp_title(234) just echoes a title like string wherever I put it on the template page.

I also tried just editing the functions.php where the title is made:

<title><?php getTitle($wp_query->query_vars['claim_id']);?></title>

But $wp_query->query_vars['claim_id'] is null when called in the functions.

I must be totally not understanding these filters, how can i get the title to be set to the output of getTitle($wp_query->query_vars['claim_id']) ?

Upvotes: 0

Views: 4905

Answers (1)

rnevius
rnevius

Reputation: 27092

$wp_query is a global variable. To access a global variable in your code, you first need to globalize the variable with global $variable;. In your case, this means:

function assignPageTitle(){
    global $wp_query;
    return "Custome Title";
}
add_filter('wp_title', 'assignPageTitle');

There's more info about global WordPress variables in the Codex.

Upvotes: 1

Related Questions