在function.php中添加如下代码:
//添加缩略图支持 if ( function_exists('add_theme_support') )add_theme_support('post-thumbnails'); //输出缩略图地址 function post_thumbnail_src(){ global $post; if( $values = get_post_custom_values("thumb") ) { //输出自定义域图片地址 $values = get_post_custom_values("thumb"); $post_thumbnail_src = $values [0]; } elseif( has_post_thumbnail() ){ //如果发布文章时手动设置了特色图像,则优先输出它 $thumbnail_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID),'full'); $post_thumbnail_src = $thumbnail_src [0]; } else { $post_thumbnail_src = ''; ob_start(); ob_end_clean(); $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); $post_thumbnail_src = $matches [1] [0]; //获取图片链接 if(empty($post_thumbnail_src)){ //如果文章中没有图片,则显示随机图片 $random = mt_rand(1, 10); echo get_bloginfo('template_url'); echo '/images/pic/'.$random.'.jpg'; //如果文章中没有图片,则显示默认图片 //echo '/images/default_thumb.jpg'; } }; echo $post_thumbnail_src; }
最后在需要调用的地方添加如下代码:
<h3>相关文章</h3> <ul class="related_img"> <?php $post_num = 4; $exclude_id = $post->ID; $posttags = get_the_tags(); $i = 0; if ( $posttags ) { $tags = ''; foreach ( $posttags as $tag ) $tags .= $tag->term_id . ','; $args = array( 'post_status' => 'publish', 'tag__in' => explode(',', $tags), 'post__not_in' => explode(',', $exclude_id), 'caller_get_posts' => 1, 'orderby' => 'comment_date', 'posts_per_page' => $post_num ); query_posts($args); while( have_posts() ) { the_post(); ?> <li class="related_box" > <div class="r_pic"> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" target="_blank"> <img src="<?php echo post_thumbnail_src(); ?>" alt="<?php the_title(); ?>" class="thumbnail" /> </a> </div> <div class="r_title"><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" target="_blank" rel="bookmark"><?php the_title(); ?></a></div> </li> <?php $exclude_id .= ',' . $post->ID; $i ++; } wp_reset_query(); } if ( $i < $post_num ) { $cats = ''; foreach ( get_the_category() as $cat ) $cats .= $cat->cat_ID . ','; $args = array( 'category__in' => explode(',', $cats), 'post__not_in' => explode(',', $exclude_id), 'caller_get_posts' => 1, 'orderby' => 'comment_date', 'posts_per_page' => $post_num - $i ); query_posts($args); while( have_posts() ) { the_post(); ?> <li class="related_box" > <div class="r_pic"> <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" target="_blank"> <img src="<?php echo post_thumbnail_src(); ?>" alt="<?php the_title(); ?>" class="thumbnail" /> </a> </div> <div class="r_title"><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>" target="_blank" rel="bookmark"><?php the_title(); ?></a></div> </li> <?php $i++; } wp_reset_query(); } if ( $i == 0 ) echo '<div class="r_title">暂时没有相关文章!</div>'; ?> </ul>
WordPress 相关文章缩略图及标题列表
https://www.rengang.com.cn/get-wordpress-related-posts.html
「真诚赞赏,手留余香」
赞助用于本站维护,手机长按识别二维码。
任刚(rengang.com.cn)整理分享,欣赏作品版权均归原作者所有,仅供学习交流。点击上方图标与好友分享!
发表回复
要发表评论,您必须先登录。