'Recent Posts' links open in new window, without copying the 'WP_Widget_Recent_Posts' class

wordpress.stackexchange https://wordpress.stackexchange.com/questions/298689

  •  16-03-2021
  •  | 
  •  

Pregunta

I have a requirement to have links on the 'recent posts' widget open in a new window (It's not something I would implement given the choice, but I've been asked to do it). I've found out that to implement this behaviour I need to copy the class from class-wp-widget-recent-posts.php into my child theme's functions.php and modify it to create the behaviour.

For the sake of opening links in a new window this seems like a long-winded way to do it. Is there a more straightforward way that doesn't carry the potential drawbacks of re-implementing an entire class (which might break in the future if WP changes something fundamental in an update), and doesn't require modifying the original class-wp-widget-recent-posts.php file.

¿Fue útil?

Solución

No there doesn't really seem to be a better way. Just make sure your class has a new class name, the core widgets aren't 'pluggable'.

I can't see any hooks inside the Recent Posts widget that would allow changing its output, nor are there any hooks appropriate for changing a widgets output or callback function.

I've seen some techniques that involve using hooks that run between widgets to capture the output and modify it in some way, but those are fairly hacky and you won't have access to the widget's settings or the widget area's parameters.

Another approach involves replacing the callback function of the widget by modifying the global widgets variable, but that doesn't seem superior to copying the widget to me, because you have to do awkward stuff like digging into that global widgets variable to pull out the original arguments. Again it feels hacky to me, but if you're curious it's the 4th option in this article.

I wouldn't worry about the widget breaking in future versions of WordPress though. You may be copying a core widget, but for all intents and purposes this is a custom widget you'll be making and WordPress is very good about keeping backwards compatibility with things like that. If the core widget ever changes in future then you might miss out on those changes, or have to re-implement them if you want them, but it's unlikely yours will break.

Licenciado bajo: CC-BY-SA con atribución
scroll top