wordpress常用的全局变量$post代码介绍

WordPress教程 2977

在wordpress插件或主题应用开发过程中,全局变量是必须要了解的一个内容,下面要介绍的是经常会使用到的wordpress全局变量$post,全局变量$post的作用是获取当前文章的ID、标题、作者、发布时间和内容信息,在实际应用中,如编写提取文章内容首张图片的函数时,就可以使用$post全局变量。

变量代码

1
2
3
4
5
6
global $post;
echo $post->ID; //文章ID
echo $post->post_author; //文章作者ID
echo $post->post_date; //文章发布时间
echo $post->post_date_gmt; //文章发布GMT时间
echo $post->post_content; //文章内容

使用示例

获取文章首图

1
2
3
4
5
6
7
8
9
10
11
12
13
function catch_image() {
	global $post;
	$getImg = '';
	ob_start();
	ob_end_clean();
	$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
	if(isset($matches[1][0])){
		$imgUrl = $matches[1][0];
	}else{
		$imgUrl = '';
	}
	return $imgUrl;
}

代码解析:先定义全局变量$post,再通过正则匹配文章内容$post->post_content里的img标签,然后提取url。

精品推荐: