WP_GET_ATTACH_LINK的添加过滤器示例

时间:2011-05-10 作者:mrtsherman

让我先说一句,我不太了解Add\\u过滤器,但我想在这里使用它。如果没有,请告诉我。

我想修改wp_get_attachment_link 这样链接url就会更改。例如,如果我单击图库中的缩略图,而不是直接转到文件,我希望它转到www.foo。com。

所以,我想做的是替换wp\\u get\\u attachment\\u link通过add\\u filter所做的操作。但我不知道add\\u过滤器是如何工作的。如何从原始函数中获取参数?

原始函数调用

wp_get_attachment_link($id, $size, $permalink, $icon, $text);
过滤器

add_filter( \'wp_get_attachment_link\', \'modify_attachment_link\');

function modify_attachment_link() {
    //how do i access $id, $size, $permalink, $icon and $text???
    $foo = $id.$permalink;
    return $foo;
}

2 个回复
最合适的回答,由SO网友:fuxia 整理而成

查看中的函数wp-includes/post-template.php. 在这里,您可以看到您可以获得哪些信息:

apply_filters(
    \'wp_get_attachment_link\'
,   "<a href=\'$url\' title=\'$post_title\'>$link_text</a>"
,   $id
,   $size
,   $permalink
,   $icon
,   $text 
);
请注意,您无法访问$link_text 以及$_post 对象作为独立变量。缺陷缺陷

在过滤器中,不能更改参数的顺序,只能更改数字。

所以add_filter( \'wp_get_attachment_link\', \'modify_attachment_link\', 10, 2 ); 将为您提供链接标记和$id. 可用参数的最大数目为6.

函数的返回值将替换第一个参数。

更改链接URL的(未测试)示例:

/**
 * Replaces the URL for an attachment link.
 *
 * @param  string $markup     Original link markup
 * @param  int    $id         Post id
 * @param  mixed  $size       Image size, array or string
 * @param  string $permalink  URL
 * @param  bool   $icon       Use an icon?
 * @param  bool   $text       Use text?
 * @return string             New markup
 */
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 https://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\'>$link_text</a>";
}

add_filter( \'wp_get_attachment_link\', \'modify_attachment_link\', 10, 6 );
进一步阅读:

SO网友:dpgtfc

add_filter( \'wp_get_attachment_link\', \'modify_attachment_link\', 10, 5 );

function modify_attachment_link($id, $size, $permalink, $icon, $text) {
    $foo = $id.$permalink;
    return $foo;
}
请参见source.

最后两个参数是优先级和参数数。如果不指定大于1的参数数(IIRC),则会引发错误。

结束

相关推荐

how to edit attachments?

在将例如文件附加到帖子时,如何在事后编辑/删除它们?在帖子编辑器中找不到任何内容。谢谢