WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I've got a custom filter which appends the image #ID to the end of the image href, however it returns 2 x url's.

Can anybody see what i'm doing wrong?

function modify_attachment_link($markup, $id, $size, $permalink, $icon, $text) {

    $pos = strpos($markup, "href") + 6;
    $remainstring = substr($markup, $pos);
    $pos2 = strpos($remainstring, "'");
    $url = substr($remainstring, 0, $pos2);
    $url .= "#image-".$id;
    return substr_replace($markup, '' . $url . '', $pos, strlen(''));

add_filter( 'wp_get_attachment_link', 'modify_attachment_link', 10, 6 );

Kind regards. :)

share|improve this question

strlen('') in substr_replace will always evaluate to 0, which doesn't replace anything. It just inserts the new url at $pos.

You could use this:

function modify_attachment_link( $markup, $id ) {

    $pos = strpos( $markup, 'href' ) + 6;

    $remainstring = substr( $markup, $pos );
    $pos2 = strpos( $remainstring, "'" );

    $url = substr( $remainstring, 0, $pos2 );
    $url_length = strlen( $url );

    $url .= "#image-$id";
    return substr_replace( $markup, $url, $pos, $url_length );
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.