0

I am working on a site where the page titles are generated dynamically from external data sources. So obviously, Yoast SEO/WordPress SEO doesn´t know anything about the correct title, description, image etc. in the head when it outputs OpenGraph tags and more.

That should be no problem so far, as WordPress SEO supports filters to hook into the output. You can find them in this list.

Filters must go into the functions.php, I need to pass my generated data to it and then the hooks will do their magic. As I can´t use variables in add_filter() I need some way around.

I am already using this technique described by toscho to save data in static variables, so I can access them from around the whole WordPress. (This works fine for everything, except my filters.)

So my page template is calling

$saved = title_storage($event_title);

to save the dynamically generated page title into a static variable for later use.

In my functions.php I got the following:

function seo_change_title( $string )
{
   $string = title_storage();
   return $string;
}
add_filter( 'wpseo_title', 'seo_change_title', 10, 1 );

Obviously this doesn´t work. The title is stripped from the OpenGraph tags but that´s everything that changes. Although that probably means, my variable is empty.

Trying to get my head around anonymous functions and searching WPSE for solutions, but I thought it could be this easy. Am I getting something wrong here?

2

Most obvious reason could be the fact wpseo_title filter is firing before you have saved your title. Try moving title_storage() call on a earlier stage like. The wp action should be a good candidate.

  • Hm, there is little chance to calling it earlier, I guess. I need to do a GET request to an external data source, send the received data through some XSL transformation and do some fallback-stuff if some information is missing. – flomei Apr 22 '16 at 9:17
  • @flomei On what action do you currently do all that? – Z. Zlatev Apr 22 '16 at 10:46
  • In my events.php which is a user-defined template for showing this external data. – flomei Apr 22 '16 at 11:44
  • 1
    Every action after wp_head might be too late for you. Find a way to determine your requests and acquire the needed data earlier, ideally before template_redirect action. – Z. Zlatev Apr 22 '16 at 14:12
0

Just as Zlatev recommended, I tried to get my data earlier and hook into the Yoast SEO plugin earlier.

This worked fine for me. Had to write three new functions to get the desired data from my external data source, but now I have no more problems with setting title, open graph image and more.

Lesson learned: Write (wrapper) functions to have your data ready, when you need it.

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.