建站教程

建站教程

Products

当前位置:首页 > 建站教程 >

获取附件连接的函数:wp_get_attachment_image_src(WordPress图片附件地址跳转到文章页面方法)

GG网络技术分享 2025-03-18 16:12 0


获取附件连接的函数:wp_get_attachment_image_src

此函数用来获取一个图片的路径函数,此函数返回的是一个包含图片路径,宽度和高度的有序数组。

语法结构

参数

$attachment_id – 数值,必需,想要获取信息的附件ID,默认值:None
$size – 字符串,获取指定尺寸的图像,默认值:None,可选thumbnail, medium, large or full(对应后台——设置——多媒体的图像大小 ,full表示原始尺寸),或通过array(300,240)自定义图片大小。需要注意的是WordPress 2.5 以前的版本是没有 $size 参数的,只显示原始尺寸。
$icon – 布尔,可选,是否使用媒体图标来表示当前附件,比如:如果要获取的附件不是一张图片,而是,比如说视频,让$icon为真可以返回代表视频(mime type:video)的图标,否则只能返回空值。这些代表不同mime type的图片在wp-includes/images/crystal目录下

使用方法

官方示例

WordPress图片附件地址跳转到文章页面方法

WPimage

WordPress的图片附件在可打开连接的情况下会有一些意想不到的问题出现,特别是对SEO有很不利的影响,可打开连接的图片附件会有两个相同内容的url。我自己的服务器上就发现百度蜘蛛会拼命地抓取/?attachment_id=1图片附件地址,这些附件页面实际除了图片外均为空白内容,对SEO是很不友好的。所以我们有必要将这些附件地址均统一跳转到附件所属文章页面,那么如何才能自动将WordPress图片附件地址跳转到文章页面呢?请看以下代码:

将以下代码插入主题function.php文件中:

/*

重定向附件页面到文章页

代码来源: www.wpzxbj.com

*/

add_action( \'template_redirect\', \'wpse27119_template_redirect\' );

function wpse27119_template_redirect()

{

// Get out of here if not headed to an attachment page

if( ! is_attachment() ) return;

// Find the $post variable representing the page where we\'re heading

global $post;

if( empty( $post ) ) $post = get_queried_object();

// Check if post has a parent

if ($post->post_parent)

{

// Yes so find permalink of parent post

$link = get_permalink( $post->post_parent );

// Redirect attachment to the parent post

wp_redirect( $link, \'301\' );

exit(); // always call exit after wp_redirect

}

else

{

// No parent so just redirect to home page

wp_redirect( home_url(), \'301\' );

exit(); // always call exit after wp_redirect

}

}

这段代码仅对图片附件页面有效, 原理是检查附件页面是否有相应文章页,如果有就自动301跳转到文章页,如果没有就跳转到网站首页。

标签:

提交需求或反馈

Demand feedback