Simply put: Should custom meta boxes be able to output shortcodes the same way as WordPress’ native post editor?
Reason I ask is because Ive created my own custom meta box for inputting a shortcode from the Cart66 plugin in order to output an “Add To Cart” button but when I try – it only prints the text from the shortcode rather than rendering the actual button.
My current meta box:
<?php
//////////////////////////////////////////////////////////////////////
// Register Custom Post Type Meta Box -- Add To Cart Button Field //
//////////////////////////////////////////////////////////////////////
add_action( 'add_meta_boxes', 'store_button_meta_box_add' );
function store_button_meta_box_add()
{
add_meta_box( 'epr_store_button_meta_id', 'Add To Cart Button [shortcode]', 'store_button_meta_box_cb', 'epr_store', 'side', 'high' );
}
function store_button_meta_box_cb( $post )
{
$values = get_post_custom( $post->ID );
$button = isset( $values['meta_box_button_shortcode'] ) ? esc_attr( $values['meta_box_button_shortcode'][0] ) : '';
wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );
?>
<p>
<textarea name="meta_box_button_shortcode" id="meta_box_button_shortcode" row="5" style="width:100%; height:100px;text-align:left;"><?php echo esc_textarea($button); ?></textarea>
</p>
<?php
}
add_action( 'save_post', 'epr_button_meta_box_save' );
function epr_button_meta_box_save( $post_id )
{
// Bail if we're doing an auto save
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
// if our nonce isn't there, or we can't verify it, bail
if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;
// if our current user can't edit this post, bail
if( !current_user_can( 'edit_post' ) ) return;
// now we can actually save the data
$allowed = array(
'a' => array( // on allow a tags
'href' => array() // and those anchords can only have href attribute
)
);
// Probably a good idea to make sure your data is set
if( isset( $_POST['meta_box_button_shortcode'] ) )
update_post_meta( $post_id, 'meta_box_button_shortcode', wp_kses( $_POST['meta_box_button_shortcode'], $allowed ) );
}
?>
Short answer: no.
Shortcodes are for injecting content directly in the Post Content, by the user, via the Post Edit screen.
If your data are coming from a metabox, you have other, better, more efficient, and easier-to-control means of injecting content into the Post Content: primarily, the
the_content
filter (for general usage), or custom action hooks (for Themes that provide them).Using the
the_content
filter to add your code is simple:No need for a shortcode.
Also, using a filter, you don’t have to worry about your shortcode being left orphaned if the user deactivates your Plugin.
Note that, if you need to output a specific shortcode, you can use
do_shortcode( '[shortcode_name att="value"]' )