如何在wordpress数据库中检索保存的数据

How to retrieve saved data in wordpress database

我创建了一个带有自定义元框的自定义 post 类型,根据下面的代码,我知道它保存在 prefix_postmeta 上,我如何获取此数据并将其显示在页面模板上?

例如:如果我有这个POST,当我查看这个POST时,我将能够在这个POST的底部看到这个数据:

Title: THIS POST

Content: lorem ipsum

Options from meta box: the options

有人知道我该怎么做吗?的将给出想法或教程如何做到这一点? 任何建议都会有很大的帮助。请不要投反对票。谢谢,堆栈溢出的家伙。

下面的代码是我用来保存自定义元框的自定义字段的代码。

   function survey_questions_meta_save( $post_id ) {
 // Checks save status
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'survey_questions_nonce' ] ) && wp_verify_nonce( $_POST[ 'survey_questions_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';
// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
    return;
}
if ( isset( $_POST[ 'option1' ] ) ) {
  update_post_meta( $post_id, 'option1', sanitize_text_field( $_POST[ 'option1' ] ) );
}
if ( isset( $_POST[ 'option2' ] ) ) {
  update_post_meta( $post_id, 'option2', sanitize_text_field( $_POST[ 'option2' ] ) );
}
if ( isset( $_POST[ 'option3' ] ) ) {
  update_post_meta( $post_id, 'option3', sanitize_text_field( $_POST[ 'option3' ] ) );
}
if ( isset( $_POST[ 'option4' ] ) ) {
  update_post_meta( $post_id, 'option4', sanitize_text_field( $_POST[ 'option4' ] ) );
}
if ( isset( $_POST[ 'option5' ] ) ) {
  update_post_meta( $post_id, 'option5', sanitize_text_field( $_POST[ 'option5' ] ) );
}
}
  add_action( 'save_post', 'survey_questions_meta_save' );

您正在寻找 get_post_meta() 函数。

在您的页面中,您需要检索自定义 post ID,最好使用 get_the_id() 函数。

如果你在 single-{cpt-name}.php 上,你可以创建一个简单的循环,在里面你可以毫不费力地提取所有 posts 和元数据。

$post_meta = get_post_meta( get_the_ID(), 'option_name', true );

有关 Wordpress Plugin Handbook 上 post 元的更多详细信息。