0

I'm currently using the native widget-image which output content like that:

<section class="widget widget_media_image">
  <h2 class="widget-title">Some title</h2>
  <a href="https://www.example.com/">
    <img width="300" height="225" src="..."  />
  </a>
</section>

This is great, but I'd like the <h2> to be wrapped in the <a>.
Is there any way to edit the current widget image structure or do I have no alternative but to register a new widget?

This is what I need:

<section class="widget widget_media_image">
  <a href="https://www.example.com/">
    <h2 class="widget-title">Some title</h2>
    <img width="300" height="225" src="..."  />
  </a>
</section>
0

Actually, it is not the widget itself that is responsible for the broad structure. That is determined when a sidebar is registered. The widget instance itself, for instance, only stores the title. The html around it (in your case currently <h2>...</h2>, which you want to change to <a><h2>...</h2></a>) is set at the sidebar registration stage.

Now, your problem is you only want to change this structure for one specific type of widget. Luckily you can do this at the render stage. If you look at the source of the rendering function, you see a couple of filters you can use. You are looking for this one:

$params = apply_filters( 'dynamic_sidebar_params', $params );

You could use it like this:

function wpse337107_add_link_to_widget_title ($params) {
  if ($params[widget_name] == 'media_image') { // check needed if this is the correct widget name
    $params[before_title] = '<a href="https://www.example.com><h2>"';
    $params[after_title] = '</h2></a>';
    }
  return $params;
  }
add_filter ('dynamic_sidebar_params','wpse337107_add_link_to_widget_title',10,1);

Note: code not tested, so probably buggy, but I hope you get the point.

4
  • This indeed allows me to change the structure, but only by adding a new <a>. I don't want to duplicate the link, I'd like to replace the current one. Seems like I can't access the current link with this filter. – Quentin Veron May 5 '19 at 15:26
  • The current link is simply set in the widget itself. Go to the widget page on the dashboard. Find the right sidebar and the widget within it. You will see the image. Below the image is an input field for the link. Remove the link. – cjbj May 5 '19 at 19:30
  • I need to keep this link. I updated my question with the output I'm looking for. – Quentin Veron May 5 '19 at 19:39
  • You can achieve that structure with the dynamic_sidebar_params filter by attaching the </a> not to after_title but to after_widget. – cjbj May 6 '19 at 12:14

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.