定义获取内容页面第一张图片的函数,如下
function catch_that_image($pagg) {
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+?src=[\'"]([^\'"]+)[\'"].*?>/i', $pagg->post_content, $matches);
$first_img = $matches[1][0];
if(empty($first_img)) {
$first_img = "/default.png";
}
return $first_img;
}
注:
这个函数建议放在模板文件下的functions.php,根据实际应用的模板调放置位置。
- $pagg: 传递的post ,或则page的单个对象;
- ob_start():打开输出控制缓冲;
- ob_end_clean(): 清空(擦除)缓冲区并关闭输出缓冲;
- $pagg->post_content: 获取文章页面的内容;
- preg_match_all(string $pattern , string KaTeX parse error: Expected 'EOF', got '&' at position 18: …bject [, array &̲matches
[, int $flags = PREG_PATTERN_ORDER [, int o f f s e t = 0 ] ] ] ) : 执 行 一 个 全 局 正 则 表 达 式 匹 配 , , 其 中 offset = 0 ]]]):执行一个全局正则表达式匹配,,其中 offset=0]]]):执行一个全局正则表达式匹配,,其中pattern
代表要搜索的模式,, s u b j e c t 代 表 字 符 串 也 就 是 被 检 索 的 对 象 , , subject代表字符串也就是被检索的对象,, subject代表字符串也就是被检索的对象,,matches代表多维数组、输出结果为数组;
应用在随机列表中,如下:
<ul>
<?php
$args = array('numberposts' => 6, 'orderby' => 'rand', 'post_status' => 'publish', 'post_type'=>'page', 'exclude' => '3,5,69' );
$rand_pages = get_posts( $args );
foreach( $rand_pages as $pagg ) : ?>
<li>
<img src="<?php echo catch_that_image($pagg); ?>" alt="<?php echo $pagg->post_title; ?>" />
<a href="<?php echo get_page_link($pagg->ID); ?>"><?php echo $pagg->post_title; ?></a></li>
<?php endforeach; ?>
</ul>
此段代码,放置在需要增加随机文章列表的文件中。
- 这里我选择的是post类型为page的文章;
- exclude:是需要排除在外的文章id;
- ‘orderby’ => ‘rand’ ; 随机排序;
题外话:
使用下面函数
get_pages( array|string
a
r
g
s
=
a
r
r
a
y
(
)
)
获
取
p
o
s
t
类
型
为
p
a
g
e
的
一
组
对
象
参
考
h
t
t
p
s
:
/
/
d
e
v
e
l
o
p
e
r
.
w
o
r
d
p
r
e
s
s
.
o
r
g
/
r
e
f
e
r
e
n
c
e
/
f
u
n
c
t
i
o
n
s
/
g
e
t
p
a
g
e
s
/
但
是
不
晓
得
怎
么
随
机
获
取
?
?
因
为
参
数
args = array() ) 获取post类型为page的一组对象 参考https://developer.wordpress.org/reference/functions/get_pages/ 但是不晓得怎么随机获取??因为参数
args=array())获取post类型为page的一组对象参考https://developer.wordpress.org/reference/functions/getpages/但是不晓得怎么随机获取??因为参数args数组对像,好像没有可以设置随机的字段;
尝试之后还是选择了使用get_posts()函数;我的目的是随机页面列表;不介意是否随机的两个函数都可以用