I have created a custom post type with custom meta box, given the code below, I know it’s saved on prefix_postmeta, how could I get this data and display it on a page template?
for example: if I have THIS POST when I view THIS POST I will be able to see this data at the bottom of THIS POST:
Title: THIS POST
Content: lorem ipsum
Options from meta box: the options
anyone knows how can I do this? of will give the idea or a tutorial how to do this?
any suggestion will be a great help. pls don’t vote down. Thank you, stack overflow dudes.
The code below is the code I used to save the custom meta box’s custom fields.
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' );
You are looking for
get_post_meta()
function.In your page you need to retrieve the custom post ID, best using
get_the_id()
function.If you are on
single-{cpt-name}.php
you can just create a simple loop and inside you’ll be able to pull all the posts and meta without any trouble.more details on redering post meta on WordPress Plugin Handbook.