WordPress函数get_post()

WordPress函数get_post用于获取文章的数据,包括文章内容、标题、别名、摘要、发布时间等信息。

一、语法格式:

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

二、函数参数

1、$post

整数型,默认值:null

文章的ID,或对象

2、$output

字符串值,默认值:OBJECT

指定返回数据的类型,可用的值如下:

OBJECT:对象;
ARRAY_A:数组,升序排列;
ARRAY_N:数组,降序排列;

3、$filter

字符串值,默认值:raw

要应用的过滤类型

三、函数返回值

WP_Post Object (
[ID] => 121
[post_author] => 1
[post_date] => 2017-11-28 21:44:29
[post_date_gmt] => 2017-11-28 13:44:29
[post_content] => 文章内容
[post_title] => 文章标题
[post_excerpt] => 文章摘要
[post_status] => publish
[comment_status] => open
[ping_status] => closed
[post_password] =>
[post_name] => 文章别名
[to_ping] =>
[pinged] =>
[post_modified] => 2018-04-08 09:04:53
[post_modified_gmt] => 2018-04-08 01:04:53
[post_content_filtered] =>
[post_parent] => 0
[guid] => https://www.beizigen.com/?p=121
[menu_order] => 0
[post_type] => post
[post_mime_type] =>
[comment_count] => 0
[filter] => raw
)
注意返回的guid为文章原始链接,即动态URL,不会返回伪静态链接。

获取其信息 就可以用类似于 $result -> post_title 的方法,实现信息调用。

四、简单示例

获取指定ID文章内容

格式一:

<?php
    // 获取文章ID编号为10的标题名称,返回对象数据格式
    $post_id = 100; // 文章ID
    echo get_post( $post_id )->post_content; // 输出文章的内容
?>

格式二:

<?php
    // 获取文章ID编号为10的标题名称,返回字段关联数组数据格式
    $post_id = 100;
    $post = get_post($post_id, ARRAY_A); // 这样返回的值变成了数组形式
    $post_title = $post['post_title'];
    $post_date = $post['post_date'];
    $post_content = $post['post_content'];
?>

五、其他示例:

获取编号(ID)为7的文章标题:

<?php
$my_id = 7;
$post_id_7 = get_post($my_id); 
$title = $post_id_7->post_title;
?> 

也可以指定$output参数:

<?php
$my_id = 7;
$post_id_7 = get_post($my_id, ARRAY_A);
$title = $post_id_7['post_title'];
?> 
<?php
	$post = get_post( 8 );
	$title = $post->post_title;
	$excerpt = $post->post_excerpt;
	$content = $post->post_content;
?>