WordPress.org

Ready to get started?Download WordPress

Forums

Help get image link title in this function (3 posts)

  1. dbirider
    Member
    Posted 2 years ago #

    I'm using the below function (found here) so the gallery links to large size images instead of full size ones. The problem is that it removes the title in the large image link (it's still there in the gallery thumbnail). Does anyone know how I can get it back in the link?

    function oikos_get_attachment_link_filter( $content, $post_id, $size, $permalink ) {
    
        // Only do this if we're getting the file URL
        if (! $permalink) {
            // This returns an array of (url, width, height)
            $image = wp_get_attachment_image_src( $post_id, 'large' );
            $new_content = preg_replace('/href=\'(.*)\'/', 'href=\'' . $image[0] . '\'', $content );
            return $new_content;
        }
    }
    add_filter('wp_get_attachment_link', 'oikos_get_attachment_link_filter', 10, 4);
  2. keesiemeijer
    moderator
    Posted 2 years ago #

    try it with this:

    function oikos_get_attachment_link_filter( $content, $post_id, $size, $permalink ) {
    
        // Only do this if we're getting the file URL
        if (! $permalink) {
    
            $post_title = get_the_title($post_id);
    
            // This returns an array of (url, width, height)
            $image = wp_get_attachment_image_src( $post_id, 'large' );
            $new_content = preg_replace('/href=\'(.*)\'/', 'href=\'' . $image[0] . '\' title="'.$post_title.'"/', $content );
            return $new_content;
        }
    }
    add_filter('wp_get_attachment_link', 'oikos_get_attachment_link_filter', 10, 4);
  3. magicroundabout
    Member
    Posted 1 year ago #

    Hi there,

    I wrote the original post that @dbirider referred to - this problem has been pointed out in a comment.

    He's right, and my regular expression is probably the culprit. The .* is "greedy". This means that if the $image variable contains a tag like:

    <a href=''http://mysite.com/path/image.jpg'' title=''Image title''>

    then it will match (and therefore replace) everything between the first quote mark and the last quote mark. In fact, if you're image tag was using single quote marks for the src attribute, instead of double quote marks, it would delete the image too!!

    An alternative, better, dare I say RIGHT fix to my snippet would be to make the .* in the regular expression "lazy", by changing it to .*?. So the preg_replace line becomes:

    $new_content = preg_replace('/href=\'(.*?)\'/', 'href=\'' . $image[0] . '\' title="'.$post_title.'"/', $content );

    I've not tested this but you're welcome to give it a go.

    I'll update my post too. Thanks for raising this, and to @keesiemeijer for the fix.

Topic Closed

This topic has been closed to new replies.

About this Topic