实际上,即使启用了“pretty”永久链接,也可以始终使用查询参数。因此/category/sub-category/article.html/attachment/image
您可以访问/?attachment=image
. 这种“故障”的唯一情况是/category/sub-category/article.html?attachment=image
, 因为WordPress很困惑:它试图同时查询帖子和附件。然而,这很容易处理:检查请求,如果是附件,则删除其他参数。
add_action( \'parse_request\', \'wpse5015_parse_request\' );
function wpse5015_parse_request( $wp )
{
if ( array_key_exists( \'attachment\', $wp->query_vars ) ) {
unset( $wp->query_vars[\'name\'] );
unset( $wp->query_vars[\'year\'] );
unset( $wp->query_vars[\'monthnum\'] );
}
}
现在,您只需更改生成的附件URL。由于它们几乎都是正确的格式,我们可以进行一些搜索和替换:
add_filter( \'attachment_link\', \'wpse5015_attachment_link\', 10, 2 );
function wpse5015_attachment_link( $link, $id )
{
// If the attachment name is numeric, this is added to avoid page number conflicts
$link = str_replace( \'attachment/\', \'\', $link );
$attachment = get_post( $id );
$link = str_replace( \'/\' . $attachment->post_name . \'/\', \'?attachment=\' . $attachment->post_name, $link );
return $link;
}