使用WordPress函数the_post_thumbnail_url()获取特色图片缩略图URL

导语:在开发本主题的社交分享按钮时,遇到pinterest分享按钮的URL需要获取一张图片的URL,我想就使用文章内容缩略图的URL,毕竟在这个主题里每篇文章的图片都会生成文章缩略图片,大小是700*350。

但我通过百度查阅的一下,大部分介绍是这样做的的:

$img_id = get_post_thumbnail_id(); 
$img_url = wp_get_attachment_image_src($img_id);
$img_url = $img_url[0];
echo $img_url;

通过get_post_thumbnail_id()获取文章里的图片ID,然后通过wp_get_attachment_image_src()和获取的图片ID来得到图片的URL数组,但我觉得应该有更加简单的做法,于是我在英文官网上找到codex.wordpress.org/Post_Thumbnails中提到的几个函数:

其中有一个the_post_thumbnail_url()函数,它的描述是这样的:

Gets the direct image URL for the featured image of the current post, or the given Post ID.

This tag must be used within The Loop.

Use has_post_thumbnail() to check whether a Feature Image has been added to the post.

翻译成中文就是:

获当前文章的特色图片直接URL,也可以获取指定POST_ID的文章特色图片直接URL。

它必须在循环中使用。

在使用之前先检查文章是否添加特色图片,检查函数为has_post_thumbnail()。

<?php
if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
the_post_thumbnail_url();
}
?>

那么,最后我的代码就是:

<?php if ( has_post_thumbnail( ) ) { the_post_thumbnail_url('codilight_lite_single_medium' );} ?>

 

使用wordpress函数the_post_thumbnail_url()获取缩略图URL
WordPressLeaf.com

所以,如果你使用了本主题,请记得要给每篇文章都加上特色图片。

另外,本站主题上传图片时会自动生成四张自定义的缩略图,分别是:

codilight_lite_block_small, 90, 60 列表文章标题缩略图

codilight_lite_block_1_medium, 250, 170 列表文章标题缩略图

codilight_lite_block_2_medium, 325, 170 网格文章标题缩略图

codilight_lite_single_medium, 700, 350 文章内容缩略图

目前在“使用WordPress函数the_post_thumbnail_url()获取特色图片缩略图URL”上有2条评论

加加加进行回复 取消回复

邮箱地址不会被公开。 必填项已用*标注