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

时间:2011-11-04 20:14:42

标签: 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"]);
}

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

1 个答案:

答案 0 :(得分:10)

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

有两个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();

要小心谨慎,避免混淆: 省略get_post_meta中的布尔值将使它返回一个数组而不是一个字符串。 get_post_custom_values始终返回一个数组,这就是为什么在上面的示例中,我们回显$birth_date[0],而不是$birth_date

此刻,我并不是100%肯定,$post->ID是否会按照上述预期运作。如果没有,请将其替换为get_the_ID()。两者都应该有效,人们肯定会这样做。可以测试一下,但节省了自己的时间......

为了完整起见,请检查WP_Query上的codex以获取更多查询参数并正确使用。

相关问题