0

Okay so I have a method within a class which looks like

$this->addToSitemap('page', $urls);

This is used to append extra pages to the Yoast Sitemap. Here 'page' is the type of sitemap within yoast and $urls are the new urls. This method looks like this

public function addToSitemap($type = '', $links = array())
{
    $CustomSitemaps = $this;
    add_filter( "wpseo_sitemap_{type}_content", function() use 
    (&$CustomSitemaps) { return $CustomSitemaps->parseLinks($links); } );
}

Now here I am using an anonymous function because I need to pass the $links variable to the callback.

I am using $CustomSitemaps = $this; because an anonymous function does not allow $this. But for some reason his is still not working. If i do this

public function addToSitemap($type = '', $links = array())
{
    $CustomSitemaps = $this;
    add_filter( "wpseo_sitemap_{type}_content", function() use 
    (&$CustomSitemaps) { var_dump($CustomSitemaps->parseLinks($links)); 
    die(); return $CustomSitemaps->parseLinks($links); } );
}

I see no nothin dumping on the screen. But if I do below $CustomSitemaps = $this; I do see it

  • As far as I'm aware $this should work inside an anonymous callback in PHP 5.4+. Is it not working for you, or are you targeting an earlier version? Are you certain that this is the issue? I notice that the filter name is incorrect, which would explain why your code isn't working. {type} is supposed to be replaced with the type of sitemap you're targeting, eg. wpseo_sitemap_post_content. – Jacob Peattie Dec 31 '18 at 14:42
  • Well if you see I am using this method by $this->addToSitemap('page', $urls); I pass page as the first parameter hence the {type} in the hook becomes page. So the hook is correct – Fahad Sohail Dec 31 '18 at 14:55
  • You're not using the type variable in the filter name though. If you're trying to put the variable in the string, you're missing the $. It needs to be "wpseo_sitemap_{$type}_content" for that to work. – Jacob Peattie Dec 31 '18 at 15:02
  • thankyou!!! okay so now when i var_dump i see the dump but it is null. So for some reason the method parselinks is returning null – Fahad Sohail Dec 31 '18 at 15:10
  • You don't need to pass by reference if it's an object, the & is unnecessary – Tom J Nowell Dec 31 '18 at 17:01

Your Answer

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

Browse other questions tagged or ask your own question.