drj26159 2012-04-16 18:23
浏览 56
已采纳

WordPress:add_filter for wp_get_attachment_link ADD target param

So I'm trying to figure out how to modify the wp_get_attachment_link function with a filter. I'd like to be able to add the target='_blank' attribute to the anchor.

This is what I've tried but it isn't working:

function modify_attachment_link( $markup, $id, $size, $permalink, $icon, $text )
{
    // We need just thumbnails.
    if ( 'thumbnail' !== $size )
    {   // Return the original string untouched.
        return $markup;
    }

    // We have stored the new URL in a post meta field.
    // See http://wordpress.stackexchange.com/q/3097 for an example.
    $new_url = get_post_meta( $id, 'extra_url', TRUE );

    if ( empty ( $new_url ) )
    {   // There is no URL.
        return $markup;
    }

    // Recreate the missing information.
    $_post      = & get_post( $id );
    $post_title = esc_attr( $_post->post_title );

    if ( $text ) 
    {
        $link_text = esc_attr( $text );
    } 
    elseif ( 
           ( is_int( $size )    && $size != 0 ) 
        or ( is_string( $size ) && $size != 'none' ) 
        or $size != FALSE 
    ) 
    {
        $link_text = wp_get_attachment_image( $id, $size, $icon );
    } 
    else 
    {
        $link_text = '';
    }

    if ( trim( $link_text ) == '' )
    {
        $link_text = $_post->post_title;
    }

    return "<a href='$new_url' title='$post_title' target='_blank'>$link_text</a>";
}

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

Perhaps some of what's going on here isn't even useful, but I really need the target attribute.

  • 写回答

1条回答 默认 最新

  • drngnh708353 2012-04-16 22:46
    关注

    Something like this should work assuming there isn't already a "target" attribute in the link. If there is then this would insert a second one.

    <?php
    function modify_attachment_link($markup) {
        return preg_replace('/^<a([^>]+)>(.*)$/', '<a\\1 target="_blank">\\2', $markup);
    }
    add_filter( 'wp_get_attachment_link', 'modify_attachment_link', 10, 6 );
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀