wordpress自动调用文章缩略图的方法总结
一、自动显示文章第一张图片
在当前使用的主题模板的functions.php文件<?php和?>之前添加以下代码:
- function catch_that_image() {
- global $post, $posts;
- $first_img = '';
- ob_start();
- ob_end_clean();
- $output = preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $post->post_content, $matches);
- $first_img = $matches [1] [0];
- if(emptyempty($first_img)){
- $first_img = "/images/default.jpg";
- }
- return $first_img;
- }
在当前主题模板的index.php文件的内容代码前或后添加以下代码:
<?php echo catch_that_image() ?>
二、文章列表页自动调用文章缩略图
在外观–编辑里头找到functions.php,加入以下这个函数:
- function emtx_auto_thumbnail($pID,$thumb='thumbnail') {
- $blogimg = FALSE;
- if (has_post_thumbnail()) {
- $blogimg = wp_get_attachment_image_src(get_post_thumbnail_id($pID),$thumb);
- $blogimg = $blogimg[0];
- } elseif ($postimages = get_children("post_parent=$pID&post_type=attachment&post_mime_type=image&numberposts=0")) {
- foreach($postimages as $postimage) {
- $blogimg = wp_get_attachment_image_src($postimage->ID, $thumb);
- $blogimg = $blogimg[0];
- }
- } elseif (preg_match('/<img [^>]*src=["|']([^"|']+)/i', get_the_content(), $match) != FALSE) {
- $blogimg = $match[1];
- }
- if($blogimg) {
- $blogimg = '<a href="'. get_permalink().'"><img src="'.$blogimg.'" alt="'.get_the_title().'" class="alignleft wp-post-image" /></a>';
- }
- return $blogimg;
-
- }
然后在相应的模板文件里面调用缩略图的地方做个修改,把原来调用the_post_thumbnail的地方按照实际需求改为诸如下面这样的代码即可:
- <?php if(emtx_auto_thumbnail($post->ID) ) {
- echo emtx_auto_thumbnail($post->ID);
- } ?>
三、后台所有文章列表显示缩略图
打开你主题的functions.php文件添加如下代码:
- if ( !function_exists('fb_AddThumbColumn') && function_exists('add_theme_support') ) {
-
-
- add_theme_support('post-thumbnails', array( 'post', 'page' ) );
-
- function fb_AddThumbColumn($cols) {
-
- $cols['thumbnail'] = __('Thumbnail');
-
- return $cols;
- }
-
- function fb_AddThumbValue($column_name, $post_id) {
-
- $width = (int) 35;
- $height = (int) 35;
-
- if ( 'thumbnail' == $column_name ) {
-
- $thumbnail_id = get_post_meta( $post_id, '_thumbnail_id', true );
-
- $attachments = get_children( array('post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image') ); www.111Cn.net
- if ($thumbnail_id)
- $thumb = wp_get_attachment_image( $thumbnail_id, array($width, $height), true );
- elseif ($attachments) {
- foreach ( $attachments as $attachment_id => $attachment ) {
- $thumb = wp_get_attachment_image( $attachment_id, array($width, $height), true );
- }
- }
- if ( isset($thumb) && $thumb ) {
- echo $thumb;
- } else {
- echo __('None');
- }
- }
- }
-
-
- add_filter( 'manage_posts_columns', 'fb_AddThumbColumn' );
- add_action( 'manage_posts_custom_column', 'fb_AddThumbValue', 10, 2 );
-
-
- add_filter( 'manage_pages_columns', 'fb_AddThumbColumn' );
- add_action( 'manage_pages_custom_column', 'fb_AddThumbValue', 10, 2 );
- }