建站教程

建站教程

Products

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

WordPress获取文章缩略图URL(WordPress内置图片仓库制作缩略图的做法)

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


WordPress获取文章缩略图URL

get_the_post_thumbnail_url

以url的形式返回指定文章特色图片。

参数

  1. post 数字|WP_Post对象|可选 文章id、文章对象
  2. size 字符串|数字 缩略图尺寸

源码

File: wp-includes/post-thumbnail-template.php 223行

function get_the_post_thumbnail_url( $post = null, $size = 'post-thumbnail' ) {

$post_thumbnail_id = get_post_thumbnail_id( $post );

if ( ! $post_thumbnail_id ) {

return false;

}

return wp_get_attachment_image_url( $post_thumbnail_id, $size );

}

函数解析

1.根据文章获取文章缩略图

函数接收的参数 $post 可以是文章id,也可以是wp的文章对象:

<img src="<?php echo get_the_post_thumbnail_url($post_id);?>"/> //文章ID

<img src="<?php echo get_the_post_thumbnail_url($post);?>"/>//文章对象

2.在主循环中使用


如果是在主循环中使用,不需要传递任何参数,直接:

echo get_the_post_thumbnail_url();

3.指定尺寸

a.全图,不是缩略图

echo get_the_post_thumbnail_url($post_id,'full');

b.缩略图

默认就是缩略图,当然你也可以输入:

echo get_the_post_thumbnail_url($post_id,'thumbnail');

WordPress内置图片仓库制作缩略图的做法

WordPress 不仅是博客, 很多时候 WordPress 还被用作为 CMS (内容管理系统). 博主们喜欢为每个文章加上统一大小的缩略图, 尤其是信息类平台. 其中比较常用的处理办法是用 custom field 向文章插入图片, 通过上传大小一致的小图或者使用 phpThumb 等工具生成缩略图。

2.7 开始, WordPress 大幅提升多媒体功能, 越来越多人使用 WP 的内置图片仓库. 对这些用户来说, 制作缩略图变得并不那么困难, 在上传图片的时候就会默认生成 150x150 规格的小图 (如果图片高度/宽度不足 150px, 使用原高度/宽度). 那我们可以充分利用这个功能, 在文章列表上加上这个图片作为缩略图. 这样处理各有利弊, 好处是简单, 智能 (不用每次输入缩略图), 坏处是消耗服务器流量.

Okay, 现在要做的就是提取上传生成的小图片, 并放置在文章的适当位置. 我创建了一个文件 thumb.php, 图片获取和调用一起处理, 文件内容如下.

代码如下:

<?php

$args = array(

\'numberposts\' => 1,

\'order\'=> \'ASC\',

\'post_mime_type\' => \'image\',

\'post_parent\' => $post->ID,

\'post_status\' => null,

\'post_type\' => \'attachment\'

);

$attachments = get_children($args);

$imageUrl = \'\';

if($attachments) {

$image = array_pop($attachments);

$imageSrc = wp_get_attachment_image_src($image->ID, \'thumbnail\');

$imageUrl = $imageSrc[0];

} else {

$imageUrl = get_bloginfo(\'template_url\') . \'/img/default.gif\';

}

?>

<a href=\"<?php the_permalink() ?>\"><img class=\"left\" src=\"<?php _fcksavedurl=\"\"<?php\" _fcksavedurl=\"\"<?php\" echo $imageUrl; ?>\" alt=\"<?php the_title(); ?>\" width=\"150\" height=\"150\" /></a>

这段代码会去找第一个上传的图片缩略图 (如果第一个图片被删除, 则找第二个的, 如此类推...), 如果找不到任何上传图片则使用默认图片

然后在文章列表 index.php, 存档页面 archive.php 和搜索页面 search.php 中调用, 调用代码如下.

代码如下:

<?php include(\'thumb.php\'); the_content(\'Read More...\'); ?>

这段代码是把图片放在文章内容前面, 图片如何摆放需要用 CSS 调整一下布局, 这里就不多说了.

以上就是如何使用WordPress内置图片仓库制作缩略图的详细内容,更多请关注网站的其它相关文章!

WordPress内置图片仓库制作缩略图的做法 (https://www.wpmee.com/) WordPress使用教程 第1张

标签:

提交需求或反馈

Demand feedback