最近工作比较忙,好长时间没有更新博客了,都要长草了。抽了点时间做了这么个小功能,我将其命名为“图像盒子模块”,主要是获取的置顶文章,当然你也可以修改代码获取其他文章。由于设置的置顶文章可能过多,这里随机获取了 5 篇置顶文章。显示效果如下图所示。

代码应该是使用与所有 WordPress 主题的,具体我没有测试。大家自行测试下即可。下面简单说下代码部署方式。
新增 module_img_box_posts.php 核心文件
新建一个名为 module_img_box_posts.php 的文件,并将如下代码丢到文件中去:
<?php
/**
* 首页置顶文章图像盒子模块
* 蝈蝈要安静——一个不学无术的伪程序员
* https://blog.quietguoguo.com
*/
?>
<section id="img-box-posts">
<?php
$return ="";
$query_post = array(
'posts_per_page' => 5,
'ignore_sticky_posts' => 1,
'post_status' => 'publish',
'post_type' => 'post',
'orderby' => 'rand',
'post__in' => get_option('sticky_posts')
);
query_posts($query_post);
while(have_posts()):the_post();
$sticky_thumb = _get_post_thumbnail();
echo '<a target="_blank" href="'.get_permalink().'" title="'.get_the_title().'-'.get_bloginfo('name').'">'.$sticky_thumb.'</a>';
endwhile;
wp_reset_query();
?>
</section>
然后将该文件丢到主题文件夹下。DUX 主题的话丢到主题文件夹下的 modules 文件夹中即可。具体位置不做强制要求,后面前端调用时路径正确即可。
前端引用代码
直接将一下代码丢到主题的 index.php 文件中去即可:
<!-- 首页置顶文章图像盒子模块 -->
<?php
include get_stylesheet_directory() . '/modules/module_img_box_posts.php';
?>
由于我自己在主题后台设置了开启选项,这里分享一下方法。DUX 主题或其他使用 OptionsFramework 框架的都可以使用。
<!-- 首页置顶文章图像盒子模块 -->
<?php
if( QGG_options('img_box_posts_open') ){
include get_stylesheet_directory() . '/modules/module_img_box_posts.php';
}
?>
然后再主题的 options.php 文件中加入如下代码即可:
// 首页置顶文章图像盒子模块
$options[] = array(
'name' => __('置顶文章图像盒子', 'QGG'),
'desc' => __('开启', 'QGG'),
'id' => 'img_box_posts_open',
'std' => true,
'type' => 'checkbox'
);
修改前注意看下这篇文章:https://zibuyu.life/3171.html
CSS 样式文件
按上述操作一步步做下来,你的网站前端应该能显示出调取的文章了。下面简单分享下我调整的 CSS 样式。你也可以自行调整适合自己主题的其他样式。
/** ====================置顶文章图像盒子样式==================== */
.content #img-box-posts{
height: 240px;
background: #fff;
border-radius: 9px;
margin: 20px 0 0;
overflow: hidden;
}
.content #img-box-posts a{
display: block;
}
.content #img-box-posts a:first-child{
float: left;
margin: 0;
width: 50%;
height: 240px;
overflow: hidden;
text-align: center;
vertical-align: middle;
}
.content #img-box-posts a{
width: 24%;
height: 117.5px;
margin: 0 0 5px 1%;
overflow: hidden;
text-align: center;
vertical-align: middle;
float: left;
}
.content #img-box-posts a img{
width: 100%;
height: 100%;
}
@media (max-width: 480px){
.content #img-box-posts{
display: none;
}
}
以上。













