wordpress 中间截取缩略图
时间 : 2023-12-06 12:43:02声明: : 文章内容来自网络,不保证准确性,请自行甄别信息有效性
最佳答案
在WordPress中,你可以使用以下方法来实现中间截取缩略图的功能:
第一种方法是使用内置的函数`add_theme_support`来启用缩略图功能。在主题的`functions.php`文件中添加以下代码:
```php
add_theme_support('post-thumbnails');
这将启用缩略图功能,并在文章编辑页面中显示缩略图选项。
第二种方法是使用自定义函数来截取中间部分的缩略图。在主题的`functions.php`文件中添加以下代码:
```php
function custom_get_middle_thumbnail($post_id, $width, $height) {
$thumbnail_id = get_post_thumbnail_id($post_id);
$thumbnail_info = wp_get_attachment_image_src($thumbnail_id, 'full');
if ($thumbnail_info) {
$image_path = $thumbnail_info[0];
$image_width = $thumbnail_info[1];
$image_height = $thumbnail_info[2];
$middle_x = floor($image_width / 2) - floor($width / 2);
$middle_y = floor($image_height / 2) - floor($height / 2);
if ($middle_x >= 0 && $middle_y >= 0) {
$middle_image = wp_get_image_editor($image_path);
$middle_image->crop($width, $height, $middle_x, $middle_y);
$middle_image_path = $middle_image->generate_filename();
$middle_image->save($middle_image_path);
$attachment = array(
'post_mime_type' => 'image/jpeg',
'post_title' => basename($middle_image_path),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment($attachment, $middle_image_path, $post_id);
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata($attach_id, $middle_image_path);
wp_update_attachment_metadata($attach_id, $attach_data);
return $attach_id;
}
}
return false;
}
这个函数接受三个参数:文章ID,截取缩略图的宽度和高度。它会先获取文章的缩略图ID,然后根据缩略图的路径和尺寸计算截取的位置,最后使用`wp_get_image_editor`和`crop`方法来截取中间部分的缩略图,并保存为新的附件。返回截取缩略图的附件ID。
最后,在主题的模板文件中,你可以使用以下代码来显示中间截取的缩略图:
```php
$post_thumbnail_id = custom_get_middle_thumbnail(get_the_ID(), 300, 200);
if ($post_thumbnail_id) {
echo wp_get_attachment_image($post_thumbnail_id, 'medium');
}
这个例子中,缩略图的宽度和高度分别为300和200像素。你可以根据需要自行调整。
其他答案
在WordPress中,截取缩略图有多种方法可供选择。下面是两种常用的方法:
方法一:使用WordPress自带函数
WordPress有一个内置的函数`the_post_thumbnail()`可用于输出文章的特色图像(缩略图)。可以在主题文件中的文章循环中使用这个函数来截取并显示缩略图。
首先,确保你已经设置了文章的特色图像。在文章编辑页面的右侧,你可以找到“特色图像”框,选择或上传你想要用作缩略图的图片。
然后,在需要显示缩略图的地方,使用如下代码:
```php
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail();
}
?>
这段代码会检查当前文章是否有设置特色图像,如果有,则输出缩略图。
如果你想自定义缩略图的尺寸,可以在函数中添加参数,例如:
```php
<?php
if ( has_post_thumbnail() ) {
the_post_thumbnail( 'thumbnail' ); // 缩略图尺寸为默认的缩略图尺寸
the_post_thumbnail( array( 200, 200 ) ); // 缩略图尺寸自定义为200x200像素
}
?>
方法二:使用自定义字段
另一种截取缩略图的方式是使用自定义字段。首先,在文章编辑页面的右上方,点击“选项”按钮,然后选择“自定义字段”。
在“自定义字段”框中,添加一个新字段,字段名称设为`thumbnail`,字段值则为缩略图的图片地址。
接下来,在需要显示缩略图的地方,使用如下代码:
```php
<?php
$thumbnail_url = get_post_meta( get_the_ID(), 'thumbnail', true );
if ( $thumbnail_url ) {
echo '<img src="' . esc_url( $thumbnail_url ) . '" alt="缩略图">';
}
?>
这段代码会获取自定义字段`thumbnail`的值(即缩略图的图片地址),如果有值则输出图片标签。
这两种方法中的任何一种都可以用于截取并显示WordPress文章的缩略图。选择哪一种方法取决于你的具体需求和主题实现的方式。
https/SSL证书广告优选IDC>>
推荐主题模板更多>>
推荐文章