WordPress 调用页面信息(内容、特色图片等)的方法

WordPress 调用页面信息(内容、特色图片等)的方法

在使用Wordpress开发主题时,我们经常遇到调用指定页面信息的需求,诸如在首页调用关于我们信息等,本文就分享一下在WordPress中调用指定页面信息的方法。

WordPress 调用页面的标题及内容等信息

WordPress中可以通过 get_post() 函数,来获得指定页面的信息,包括页面的内容、标题信息。

这里说明一下,很多文章介绍的是 get_page() 函数,但实际上这个函数在 3.5 版本之后已经被弃用了,正确做法是使用 get_post() 函数。

语法

get_post( int|WP_Post|null $post = null, string $output = OBJECT, string $filter = 'raw' )

参数

$post

( int |  | null ) (可选) 帖子 ID 或帖子对象。nullfalse,0和其他 PHP 错误值返回循环内的当前全局帖子。指向不存在的帖子的数字有效帖子 ID 返回null。默认为全局 $post。

默认值:null

$out

( string ) (可选) 所需的返回类型。OBJECT、ARRAY_A 或 ARRAY_N 之一,分别对应于对象、关联数组或数值数组。

默认值:对象

$filter

( string ) (可选) 要应用的过滤器类型。 ‘raw’, ‘edit’, ‘db’, or ‘display’.

默认值:“raw”

返回

WP_Post Object
(
    [ID] =>
    [post_author] =>
    [post_date] => 
    [post_date_gmt] => 
    [post_content] => 
    [post_title] => 
    [post_excerpt] => 
    [post_status] =>
    [comment_status] =>
    [ping_status] => 
    [post_password] => 
    [post_name] =>
    [to_ping] => 
    [pinged] => 
    [post_modified] => 
    [post_modified_gmt] =>
    [post_content_filtered] => 
    [post_parent] => 
    [guid] => 
    [menu_order] =>
    [post_type] =>
    [post_mime_type] => 
    [comment_count] =>
    [filter] =>
)

示例:输出 ID 为 7 的页面标题

$post = get_post( 7 ); 
$title = $post->post_title;
echo $title;


WordPress 调用页面特色图片

通过上文可知,get_post()函数返回的对象属性中并不包含特色图片字段,我们可以通过get_the_post_thumbnail_url()函数来输出页面特色图片或者获取页面图片的URL链接。

语法

get_the_post_thumbnail_url( int|WP_Post $post = null, string|int[] $size = 'post-thumbnail' )

参数

$post

( int |  ) (可选) 帖子 ID 或帖子对象。默认是全局的$post

默认值:空

$size

( string | int[] ) (可选) 图像尺寸。

默认值:“post-thumbnail

返回

(string|false) 帖子缩略图 URL,如果没有可用的图像,则为 false。如果$size不匹配任何注册的图像大小,将返回原始图像 URL。

示例:输出 ID 为 236 的页面特色图片

$thumbnail_url = get_the_post_thumbnail_url( 236 ); 
echo $thumbnail_url;

WordPress 调用页面信息(内容、特色图片等)的方法

相关文章:

你感兴趣的文章:

标签云: