admin管理员组

文章数量:1429136

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="/">
    <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="/">
    <h2 class="widget-title">Some title</h2>
    <img width="300" height="225" src="..."  />
  </a>
</section>

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/">
    <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/">
    <h2 class="widget-title">Some title</h2>
    <img width="300" height="225" src="..."  />
  </a>
</section>
Share Improve this question edited May 5, 2019 at 19:40 Quentin asked May 5, 2019 at 10:19 QuentinQuentin 158 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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><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.

本文标签: filtersWidget image reorganize layout