1

wp_get_attachment_linkそのため、フィルターを使用して関数を変更する方法を見つけようとしています。target='_blank'アンカーに属性を追加できるようにしたいと思います。

これは私が試したものですが、うまくいきません:

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 );

ここで行われていることのいくつかは役に立たないかもしれませんが、私にはこのtarget属性が本当に必要です。

4

1 に答える 1

4

このようなものは、リンクに「ターゲット」属性がまだないと仮定して機能するはずです。存在する場合、これは 2 番目のものを挿入します。

<?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 );
?>
于 2012-04-16T22:46:13.757 に答える