Skip to content

Instantly share code, notes, and snippets.

@carlodaniele
carlodaniele / add-metabox.php
Last active Feb 7, 2016
Add meta box callback function
View add-metabox.php
<?php
/**
* Add meta box
*
* @param post $post The post object
* @link https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes
*/
function food_add_meta_boxes( $post ){
add_meta_box( 'food_meta_box', __( 'Nutrition facts', 'food_example_plugin' ), 'food_build_meta_box', 'food', 'side', 'low' );
}
View build-custom-field-meta-box.php
<?php
/**
* Build custom field meta box
*
* @param post $post The post object
*/
function food_build_meta_box( $post ){
// our code here
}
View wp-nonce-field.php
<?php
wp_nonce_field( basename( __FILE__ ), 'food_meta_box_nonce' );
View get-post-meta.php
<?php
// retrieve the _food_cholesterol current value
$current_cholesterol = get_post_meta( $post->ID, '_food_cholesterol', true );
// retrieve the _food_carbohydrates current value
$current_carbohydrates = get_post_meta( $post->ID, '_food_carbohydrates', true );
// stores _food_vitamins array
$current_vitamins = ( get_post_meta( $post->ID, '_food_vitamins', true ) ) ? get_post_meta( $post->ID, '_food_vitamins', true ) : array();
View input-text.php
?>
<div class='inside'>
<h3><?php _e( 'Carbohydrates', 'food_example_plugin' ); ?></h3>
<p>
<input type="text" name="carbohydrates" value="<?php echo $current_carbohydrates; ?>" />
</p>
</div>
<?php
View input-radio.php
<h3><?php _e( 'Cholesterol', 'food_example_plugin' ); ?></h3>
<p>
<input type="radio" name="cholesterol" value="0" <?php checked( $current_cholesterol, '0' ); ?> /> Yes<br />
<input type="radio" name="cholesterol" value="1" <?php checked( $current_cholesterol, '1' ); ?> /> No
</p>
View input-checkbox.php
<h3><?php _e( 'Vitamins', 'food_example_plugin' ); ?></h3>
<p>
<input type="checkbox" name="vitamins[]" value="Vitamin A" <?php checked( ( in_array( 'Vitamin A', $current_vitamins ) ) ? 'Vitamin A' : '', 'Vitamin A' ); ?> />Vitamin A <br />
<input type="checkbox" name="vitamins[]" value="Thiamin (B1)" <?php checked( ( in_array( 'Thiamin (B1)', $current_vitamins ) ) ? 'Thiamin (B1)' : '', 'Thiamin (B1)' ); ?> />Thiamin (B1) <br />
<!-- more vitamins here -->
</p>
View ternary-operator.php
<?php
( in_array( 'Thiamin (B1)', $current_vitamins ) ) ? 'Thiamin (B1)' : ''
View food-build-meta-box.php
<?php
/**
* Build custom field meta box
*
* @param post $post The post object
*/
function food_build_meta_box( $post ){
// make sure the form request comes from WordPress
wp_nonce_field( basename( __FILE__ ), 'food_meta_box_nonce' );
View save-post-food.php
<?php
/**
* Store custom field meta box data
*
* @param int $post_id The post ID.
*/
function food_save_meta_boxes_data( $post_id ){
// code here
}
add_action( 'save_post_food', 'food_save_meta_boxes_data', 10, 2 );
You can’t perform that action at this time.