WordPress 特色封面图像开启与使用

wordpress 特色图像可以用于分类页面或者网站首页调用文章缩略图时,指定调用某张图片,实现自定义封面的效果。WORDPRESS程序默认是不支持特色图像功能,所以我们需要开启特色图像功能。

开启特色图像功能

wordpress 特色图像开启方法很简单,只需要在主题的functions.php中添加如下代码:

//特色图像
add_theme_support( "post-thumbnails" );

这种开启代码可以让后台文章和PAGE页面,同时拥有特色图像功能。如果只想单独开启某个类型,可以使用以下的代码:

add_theme_support( 'post-thumbnails', array( 'post' ) ); // 在单篇文章中开启该功能
add_theme_support( 'post-thumbnails', array( 'page' ) ); //在页面文章中开启该功能

为了控制缩略图大小,我们还可以用下面的这些代码来控制,将这些代码放置在上面刚添加的代码后面。

set_post_thumbnail_size( 155, 110, true ); // 设置默认的缩略图大小尺寸
add_image_size( 'one', 155, 110, true ); // 设置标记为”one”的缩略图尺寸,这里的one应该是数组下标
add_image_size( 'two', 350, 248, true );
add_image_size( 'big', 546, 387, true );

特色图像的使用

在wordpress首页模板或者分类模板中使用以下代码调用特色图像:(自行修改代码里的尺寸数字)

<?php
if ( has_post_thumbnail() ) {
	the_post_thumbnail(
		array(296,296),
		array(
			'alt'=> trim(strip_tags( $post->post_title )),
			'class' => 'thumbimg'
		)
	);
} else {
?>
<img src="<?php echo get_first_image(); ?>" alt="<?php the_title(); ?>" width="296px" height="296px"/>
<?php
	}
?>

上面的代码是通常调用特色图片的方法,我们也可以使用以下的代码来调用指定的特色图片。

<?php
	the_post_thumbnail( 'big' );
?>

或者调用设置的标记为two的那张缩略图

<?php
	$thumbID = get_the_post_thumbnail( $post->ID, 'two', $imgsrcparam );
?>
<?php
	echo "$thumbID";
?>

这样,在网站后台发布文章时,在文章编辑器右侧面底部就会有一个【特色图片】上传按钮,就可以给文章上传一个指定的图片作为封面图片了。

posted @ 2022-11-20 21:18  幻月无名  阅读(287)  评论(0编辑  收藏  举报