要求,先根据tags标签调用相关内容,没有tags就调用分类,没有分类就随机文章。
关于缩略图,有特色图片就显示特色图,没有就自动调用文章内容第一张图片当缩略图展示:
先看例图,
这里分两部分代码:一、functions.php内放如下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
/** * functions.php 部分:相关文章逻辑和图片处理函数 */ // 获取相关文章列表(标签 > 分类 > 全站随机) function get_related_posts($post_num = 4) { global $post; $exclude_ids = array($post->ID); $related_posts = array(); $i = 0; // 第 1 梯度:标签 $posttags = get_the_tags($post->ID); if ($posttags) { $tag_ids = wp_list_pluck($posttags, 'term_id'); $tag_query = new WP_Query(array( 'post_status' => 'publish', 'tag__in' => $tag_ids, 'post__not_in' => $exclude_ids, 'posts_per_page' => $post_num, 'ignore_sticky_posts' => true, 'orderby' => 'date', 'order' => 'DESC', 'no_found_rows' => true, )); while ($tag_query->have_posts()) { $tag_query->the_post(); $related_posts[] = get_the_ID(); $exclude_ids[] = get_the_ID(); $i++; } wp_reset_postdata(); } // 第 2 梯度:分类 if ($i < $post_num) { $categories = get_the_category($post->ID); if ($categories) { $cat_ids = wp_list_pluck($categories, 'term_id'); $cat_query = new WP_Query(array( 'post_status' => 'publish', 'category__in' => $cat_ids, 'post__not_in' => $exclude_ids, 'posts_per_page' => $post_num - $i, 'ignore_sticky_posts' => true, 'orderby' => 'date', 'order' => 'DESC', 'no_found_rows' => true, )); while ($cat_query->have_posts()) { $cat_query->the_post(); $related_posts[] = get_the_ID(); $exclude_ids[] = get_the_ID(); $i++; } wp_reset_postdata(); } } // 第 3 梯度:随机推荐 if ($i < $post_num) { $rand_query = new WP_Query(array( 'post_status' => 'publish', 'post__not_in' => $exclude_ids, 'posts_per_page' => $post_num - $i, 'orderby' => 'rand', 'no_found_rows' => true, )); while ($rand_query->have_posts()) { $rand_query->the_post(); $related_posts[] = get_the_ID(); $i++; } wp_reset_postdata(); } return $related_posts; } // 获取特色图或正文第一张图 function get_post_thumbnail_or_first_image($post_id, $size = 'thumbnail') { if (has_post_thumbnail($post_id)) { return get_the_post_thumbnail($post_id, $size); } else { $post = get_post($post_id); if (preg_match('/<img.+src=[\"\']([^\"\']+)/i', $post->post_content, $matches)) { return '<img src="' . esc_url($matches[1]) . '" class="wp-post-image" style="object-fit:cover;width:100px;height:auto;" />'; } } return ''; } |
二、在content.php或single.php页放下面的调用代码