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

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

小菜狗
2023-05-26 / 0 评论 / 109 阅读 / 正在检测是否收录...

在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。

3

打赏

评论 (0)

取消