如何显示自定义帖子类型的自定义数据

Pru*_*rus 10 wordpress custom-post-type

我已经创建了一个自定义帖子类型.它将在Wordpress仪表板中加载得很好,我也可以保存它.现在让我们说它是一个自定义帖子类型,包含几个字符串和几个日期的数据.

我希望能够检索这些自定义帖子类型(我使用WP_Query并将post_type指定为我的自定义帖子类型的名称).当我在返回的对象上调用print_r时,对象中没有任何地方存储自定义数据(字符串和日期).我如何从数据库中检索这些?

我环顾了几个小时,但没有找到任何方法来检索这些数据.

根据要求:这是数据的存储方式:

function update_obituary(){
    global $post;
    update_post_meta($post->ID, "first_name", $_POST["first_name"]);
    update_post_meta($post->ID, "last_name", $_POST["last_name"]);
    update_post_meta($post->ID, "birth_date", $_POST["birth_date"]);
    update_post_meta($post->ID, "death_date", $_POST["death_date"]);
    update_post_meta($post->ID, "publication_date", $_POST["publication_date"]);
}
Run Code Online (Sandbox Code Playgroud)

此函数与'save_post'挂钩相关联.当我在编辑模式下重新打开自定义帖子类型实例时,将重新显示数据.这意味着它存储在数据库中,对吗?

Joh*_*lle 11

如果在编辑该类型的帖子时显示元数据,则是,它必须已成功存储在DB中.

有两个wp函数可以检索自定义帖子类型的元数据:get_post_custom_valuesget_post_meta.不同之处在于,它get_post_custom_values可以访问非唯一的自定义字段,即具有多个与单个键关联的值的字段.你也可以选择将它用于独特的领域 - 品味问题.

假设您的帖子类型被称为"ob告":

// First lets set some arguments for the query:
// Optionally, those could of course go directly into the query,
// especially, if you have no others but post type.
$args = array(
    'post_type' => 'obituary',
    'posts_per_page' => 5
    // Several more arguments could go here. Last one without a comma.
);

// Query the posts:
$obituary_query = new WP_Query($args);

// Loop through the obituaries:
while ($obituary_query->have_posts()) : $obituary_query->the_post();
    // Echo some markup
    echo '<p>';
    // As with regular posts, you can use all normal display functions, such as
    the_title();
    // Within the loop, you can access custom fields like so:
    echo get_post_meta($post->ID, 'birth_date', true); 
    // Or like so:
    $birth_date = get_post_custom_values('birth_date');
    echo $birth_date[0];
    echo '</p>'; // Markup closing tags.
endwhile;

// Reset Post Data
wp_reset_postdata();
Run Code Online (Sandbox Code Playgroud)

需要注意的是,为了避免混淆:抛出布尔值get_post_meta会使它返回一个数组而不是一个字符串.get_post_custom_values总是返回一个数组,这就是为什么,在上面的例子中,我们回应的是$birth_date[0],而不是$birth_date.

此外,我目前还不是100%肯定,是否$post->ID会在上面按预期工作.如果没有,请更换get_the_ID().两者都应该有效,人们肯定会这样做.可以测试一下,但节省自己的时间......

为了完整起见,请检查codex以WP_Query获取更多查询参数和正确用法.