0

I have a page template, used on a single page, which takes URL string parameters like this...

http://www.example.com/mypage?tags=Publishing

Facilitated like this...

// Inherit the meta target
global $wp_query;
if (isset($wp_query->query_vars['tags'])) {
  $tax_meta_key   = 'tags';
  $tax_meta_value = $wp_query->query_vars['tags'];
}

It works.

But now I also want to dynamically alter the title of the page based on the same query input.

I have read about several title filter methods. document_title_parts suits, since it only changes the title part and leaves the site name and formulation in tact.

However, the following does not work; it just results in a blank title part (not site-name part)...

<?php

// Inherit the meta target
global $wp_query;
if (isset($wp_query->query_vars['tags'])) {
  $tax_meta_key   = 'tags';
  $tax_meta_value = $wp_query->query_vars['tags'];
}

// Filter to customise page title from just "Organisation Type"
function custom_title($title_parts) {
    $title_parts['title'] = $tax_meta_value;
    return $title_parts;
}
add_filter( 'document_title_parts', 'custom_title' );

get_header();

?>

I suspect this may be down to the order in which a query_vars and a document_title_parts are executed (?) - ie. Are the vars processed after get_header?

Can I include the var in my page title?

  • 1
    $tax_meta_value is undefined from your filter callback. You can do global $tax_meta_value;, or better, move the global $wp_query; if ... part to the filter callback. – Sally CJ Jan 27 at 9:22
  • Or in that callback, you could simply use get_query_var() - $title_parts['title'] = get_query_var( 'tags' ). – Sally CJ Jan 27 at 9:33
0

If your query var tags is registered properly then the following code snippet will definitely work, I've tested it. It's a modified version of your code snippet. Please make sure to add the code to your functions.php file.

function prefix_custom_title($title_parts) {
    global $wp_query;
    if (isset($wp_query->query_vars['tags'])) {
        $title_parts['title'] = $wp_query->query_vars['tags'];
    }
    return $title_parts;
}
add_filter( 'document_title_parts', 'prefix_custom_title' );
  • This works, thanks. Though so does the above comment to simply place global $tax_meta_value; in the function. The wp_query has already been done once, above this function, so maybe best to leave it at that, and use the $tax_meta_value; it has already generated? – Robert Andrews Jan 27 at 17:35
  • I didn't expect that you'd use my given snippet with your one. When you can do things in simple 4 lines inside a function there's no point creating a global variable. Anyway good to hear that you resolved your issue (Y) – obiPlabon Jan 28 at 6:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.