When I attached images, it nested in this hierarchy of html tags :

<div id="attachment_ID" class="alignnone">
    <a class="image-ID" href="https://image-link.jpg">
        <img class="yada yada" src="https://image-link.jpg" alt="" srcset="more-image-links.jpg" sizes="yada ya da">

So I want to manipulate the anchor into <a href="post-link"

I know it is required to filter something like :

function replace_a_link( $url ) {
    // Some codes here.
    return $url;
add_filter('the_content', 'replace_a_link');

But, I don't know the exact story :/


You may try the filter wp_get_attachment_link

// definition: apply_filters( 'wp_get_attachment_link', "<a href='" . esc_url( $url ) . "'>$link_text</a>", $id, $size, $permalink, $icon, $text, $attr );

// this filter provide a max. of 7 arguments, I use 2 in the example
add_filter( 'wp_get_attachment_link', 'q363693_update_attachment_link', 10, 2 );
function q363693_update_attachment_link( $url, $id ) {
   // some codes
   $new_link = "<a href='" . get_permalink( $id ) . "'>your own text or anything you need or add more arguments to use the original text...</a>";

   return $new_link;
| improve this answer | |
  • The filter doesn't seem to hook to my attachments. If it does, I would want something like this: $new_link = "<a href='" . get_permalink( $id ) . "'>".wp_get_attachment_image( $id )."</a>"; to keep the changes similar to original result. – Hsu Pyae Naung Apr 10 at 7:04
  • Ok, how do you insert the image? Is it a default post type page or post? are you adding the image using the original editor? are you using block editor or classic editor? – simongcc Apr 10 at 7:32
  • I am using original editor, but it's a custom post type. – Hsu Pyae Naung Apr 13 at 0:30
  • I would like to confirm your procedure to insert the image. Are you adding it in the Editor thru "Add Media"? Then select "image", and then add the link by ATTACHMENT DISPLAY SETTINGS thru Link to, right? Because different method of adding image are different in manipulating the link.What effect do you want to achieve? Because if you manipulate a content image link that is being inserted by a Editor, all posts will be affected. Would you mind giving more precise examples, from you insert the link to output to the screen? And are you going to change the link for all posts or specific posts? – simongcc Apr 13 at 0:53

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.