wordpress常用的全局變量$post代碼介紹
在wordpress插件或主題應用開發過程中,全局變量是必須要了解的一個內容,下面要介紹的是經常會使用到的wordpress全局變量$post,全局變量$post的作用是獲取當前文章的ID、標題、作者、發佈時間和內容信息,在實際應用中,如編寫提取文章內容首張圖片的函數時,就可以使用$post全局變量。
變量代碼
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; //文章內容
使用示例
獲取文章首圖
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。