WordPress关于添加焦点图\特色图片并调用的方法
- 7120
- PHP
- 0
- super_dodo
- 2013/09/30
WordPress有些主题是有"设为特色图像"功能,特色图片设置之后,在列表分类页面很有用(dodo的列表页右边有缩略配图).当然你也可以在其他地方调用。
设置后会在你希望展示的地方加上该文章相关特色图片,效果不错,还是比较酷的。
但有些wordpress主题是没“设为特色图像”功能的,没有的话就在functions.php进行开启配置。
//第一步,在你的改款主题的functions.php加入如下代码:
add_theme_support( 'post-thumbnails' );
//第二步,在你的首页文件index.php模板内容位置加入:
<?php if(have_posts()):while(have_posts()):the_post(); ?>
<?php if ( has_post_thumbnail() ) { ?>
<?php the_post_thumbnail(); ?>
<?php } else {?>
<img src="<?php bloginfo('template_url'); ?>/images/xxx.jpg" />
<?php } ?>
//注:XXX.JPG为你在没有特色图片的时候显示的默认图片。
//第三步,完毕,在添加文章的时候添加特色图即可显示了。
同时附上获取文章的第一张图片的代码(自己去尝试吧):
//category-share.php里面的代码
<span class="thumImg">
<?php $thumb = getFirstImage($post->ID);if(strlen($thumb) > 0){ echo $thumb;}?>
</span>
//functions.php里面的代码
//获取文章的第一张图片链接
function getFirstImage($postId) {
$args = array(
'numberposts' => 1,
'order'=> 'ASC',
'post_mime_type' => 'image',
'post_parent' => $postId,
'post_status' => null,
'post_type' => 'attachment'
);
$attachments = get_children($args);
if(!$attachments) { return ''; } // 如果没有上传图片, 返回空字符串
// 获取缩略图中的第一个图片, 并组装成 HTML 节点返回
$image = array_pop($attachments);
$imageSrc = wp_get_attachment_image_src($image->ID, 'thumbnail');
$imageUrl = $imageSrc[0];
$html = '<img src="' . $imageUrl . '" alt="' . the_title('', '', false) . '" />';
return $html;
}
//获取文章的第一张图片链接(正则的方法)
function get_first_image(){
global $post, $posts;
$first_img = '';
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches[1][0];
if(empty($first_img)){ //Defines a default image
$first_img = "/images/common/default.jpg";
}
return $first_img;
}
Sometimes happiness is just a matter of attitude adjustment. —Susan Gale 有时候,幸福只需转变一下自己的态度。
- 高性能MySQL–MySQL基准测试
- 获取 App 用户的 5 个核心步骤
- [转]每天一个linux命令(40):ifconfig命令
- PHP使用Yii2实现Twitter(Api)授权登录并获取信息Demo
- Yii2局部关闭CSRF拦截防范策略(api接口等)
- 皇帝PK韦德回顾:首次碰面青涩 两度对飚40+
- PHP header utf8 插入header(“Content-type:text/html; charset=utf-8”);
- [转]每天一个linux命令(9):touch 命令
- 喜大普奔!沪昆高铁2016年11月30日开通通车!!!
- MySQL中的BLOB类型和TEXT类型相关说明
相关阅读
- 通过Google API客户端访问Google Play帐户报告PHP库
- PHP执行文件的压缩和解压缩方法
- 消息中间件MQ与RabbitMQ面试题
- 如何搭建一个拖垮公司的技术架构?
- Yii2中ElasticSearch的使用示例
热门文章
- 通过Google API客户端访问Google Play帐户报告PHP库
- PHP执行文件的压缩和解压缩方法
- 消息中间件MQ与RabbitMQ面试题
- 如何搭建一个拖垮公司的技术架构?
- Yii2中ElasticSearch的使用示例
最新文章
- 通过Google API客户端访问Google Play帐户报告PHP库
- PHP执行文件的压缩和解压缩方法
- 消息中间件MQ与RabbitMQ面试题
- 如何搭建一个拖垮公司的技术架构?
- Yii2中ElasticSearch的使用示例

