【问题标题】:how to display custom data from custom post types如何显示来自自定义帖子类型的自定义数据
【发布时间】:2011-11-04 20:14:41
【问题描述】:

我创建了一个自定义帖子类型。它会在 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”挂钩。当我在编辑模式下重新打开自定义帖子类型实例时,数据将重新显示。也就是说,它是存储在数据库中的,对吧?

【问题讨论】:

  • 请添加一些代码。额外的元数据如何存储?

标签: wordpress custom-post-type


【解决方案1】:

如果在编辑该类型的帖子时出现了元数据,那么是的,它必须已成功存储在数据库中。

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

假设您的帖子类型称为“讣告”:

// 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-&gt;ID 是否会按上述预期工作。如果不是,请将其替换为get_the_ID()。两者都应该工作,一个肯定会。可以测试一下,但可以节省自己的时间...

为了完整起见,请查看WP_Query 上的代码以获取更多查询参数和正确用法。

【讨论】:

  • 谢谢!这很棒!希望像我这样一直在寻找信息的人会出现在这个页面上:)
  • 不错!很好奇自己如何做到这一点,非常有帮助的答案
  • 惊讶地得到一个关于 5 年前答案的评论。不过再读一遍,WP API 的这一部分并没有太大变化——这些信息确实仍然适用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-26
  • 1970-01-01
  • 2017-01-03
  • 2016-05-07
相关资源
最近更新 更多