I have trouble to get a value from a metabox in a custom post type.
Here is how I register metabox in custom post type:
register_post_type( 'poslovi-newsletter',
array(
'labels' => array(
'name' => __( 'Poslovi newsletter' ),
'hierarchical' => false,
'singular_name' => __( 'Posalji newsletter' )
),
'public' => true,
'exclude_from_search' => true,
'menu_icon' => 'dashicons-email',
'register_meta_box_cb' => 'add_bez_oznaka_text_metabox'
)
);
And this is how I handle displaying that metabox on custom post type in dashboard, saving data, etc…
function add_bez_oznaka_text_metabox() {
add_meta_box('poslovi_newsletter_meta', 'Tekst mejla za korisnike bez oznaka', 'bez_oznaka_textarea', 'poslovi-newsletter', 'normal', 'default');
}
add_action( 'add_meta_boxes', 'add_bez_oznaka_text_metabox' );
function bez_oznaka_textarea( $post ) {
wp_nonce_field( basename( __FILE__ ), 'poslovi_newsletter_nonce' );
$poslovi_newsletter_stored_meta = get_post_meta( $post->ID );
?>
<p>
<label for="meta-textarea" class="poslovi_newsletter-row-title"><?php _e( 'Tekst mejla', 'poslovi_newsletter-textdomain' )?></label>
<textarea name="meta-textarea" id="meta-textarea" style="width: 100%; min-height: 200px;"><?php if ( isset ( $poslovi_newsletter_stored_meta['meta-textarea'] ) ) echo $poslovi_newsletter_stored_meta['meta-textarea'][0]; ?></textarea>
</p>
<?php
}
function poslovi_newsletter_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[ 'poslovi_newsletter_nonce' ] ) && wp_verify_nonce( $_POST[ 'poslovi_newsletter_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';
// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
// Checks for input and saves if needed
if( isset( $_POST[ 'meta-textarea' ] ) ) {
update_post_meta( $post_id, 'meta-textarea', $_POST[ 'meta-textarea' ] );
}
}
add_action( 'save_post', 'poslovi_newsletter_meta_save' );
Now, that all works fine. When I add new post and enter data, it saves post with that data. When I var_dump post for example, I see everything, content, title, date, etc., but I don’t see any meta data.
Also, when I do this (let’s say I want to get meta data from post with id 37422)
$meta_value = get_post_meta( 37422, 'meta-textarea', true );
var_dump($meta_value);
I get vlaue of: string(0) “”
I probably done wrong some part of code that is responsible for saving part, but can’t figure out what exactly.
Ok, so I’ve fiddled a bit with your custom post type and it works for me.
I’ve created a page template to output all the posts from the
poslovi-newsletter
post type. The php part looks like this:So your post meta value is in an array that has, among other things key with the name
meta-textarea
, and in that key the value is an array that has a single key with your desired valueI’ve typed in ‘Tessst’ to check if it’s working.
Hope this helps 🙂