Skip to content

Instantly share code, notes, and snippets.

@jeffward3283
Last active March 12, 2020 14:35
Show Gist options
  • Save jeffward3283/8107ba586edbc4c0bc56 to your computer and use it in GitHub Desktop.
Save jeffward3283/8107ba586edbc4c0bc56 to your computer and use it in GitHub Desktop.
example-wp-post-metabox.php
<?php
///////////////////////////////
# COMPLETE METABOX EXAMPLE
///////////////////////////////
///////////////////////////////
# I. ADD METABOX
///////////////////////////////
add_action( 'add_meta_boxes', 'add_meta_box_review' );
function add_meta_box_review() {
$post_types = array( 'review' );
foreach( $post_types as $post_type ) {
$metabox_id = 'review'; // id of the metabox
$metabox_title = __( 'Review' ); // title of the metabox
$metabox_callback = 'metabox_callback_review'; // name of callback function
$metabox_post_type = $post_type; // 'post', 'page', 'dashboard', 'link', 'attachment' or 'custom_post_type'
$metabox_context = 'normal'; // 'normal', 'advanced', or 'side' - The part of the page where the edit screen section should be shown
$metabox_priority = 'low'; // 'high', 'core', 'default' or 'low' - The priority within the context where the boxes should show
$metabox_args = array( 'foo' => 'value1' ); // args that will be passed into the metabox
add_meta_box( $metabox_id, $metabox_title, $metabox_callback, $metabox_post_type, $metabox_context, $metabox_priority , $metabox_args );
}
}
///////////////////////////////
# II. DISPLAY METABOX
///////////////////////////////
function metabox_callback_review( $post, $metabox = array() ) {
# Grab the args passed from the initiator
$metabox_args = (object) $metabox['args']; // echo $metabox_args->foo;
# Grab the metabox value
$field_key = 'review';
$value = get_post_meta( $post->ID, $field_key, true );
# Display the metabox content
?>
<table class="form-table">
<tbody>
<tr valign="top">
<th scope="row">
<label for="<?php echo $field_key; ?>">
<?php _e( 'Review:', 'myplugin_textdomain' ); ?>
</label>
</th>
<td>
<input type="text" id="<?php echo $field_key; ?>" name="<?php echo $field_key; ?>" value="<?php echo esc_attr( $value ); ?>" size="25" maxlength="5" />
</td>
</tr>
</tbody>
</table>
<?php
# Add an nonce field so we can verify the submission later.
$nonce_key = 'review_nonce';
$nonce_string = 'review';
wp_nonce_field( $nonce_string, $nonce_key );
}
///////////////////////////////
# III. SUBMIT METABOX
///////////////////////////////
add_action( 'save_post', 'save_metabox_review' );
add_action( 'edit_post', 'save_metabox_review', 10, 3);
function save_metabox_review( $post_id ) {
# Do not proceed during auto save
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return false;
# Verify whether or not the field is set
$field_key = 'review';
if( !isset( $_POST[ $field_key ] ) ) return false;
# Verify nonce
$nonce_key = 'review_nonce';
$nonce_string = 'review';
if( !isset( $_POST[ $nonce_key ] ) || !wp_verify_nonce( $_POST[ $nonce_key ], $nonce_string ) ) return false;
# Verify user permissions
if( !current_user_can( 'edit_post', $post_id ) ) return false;
# Verify user's permissions for the post type
$post_type = $_POST['post_type'];
$appropriate_post_types = array( 'review' );
if( in_array($post_type, $appropriate_post_types) && !current_user_can( 'edit_page', $post_id ) ) return false;
# Sanitize the field
$value = sanitize_text_field( $_POST[ $field_key ] );
# Update the meta field in the database.
update_post_meta( $post_id, $field_key, $value );
}
///////////////////////////////
# IV. ADMIN TABLE COLUMN
///////////////////////////////
/////////////////////////
# Add the Column
/////////////////////////
add_filter( 'manage_edit-'.'review'.'_columns', 'add_column_review' );
function add_column_review($columns) {
# Append the column after the title column
if(!empty($columns['title'])){
$new_array = array( 'review' => __( 'Review', 'my_textdomain' ) );
$index = (array_search('title', array_keys($columns)) + 1);
$columns = array_slice($columns, 0, $index, true)
+ $new_array
+ array_slice($columns, $index, count($columns) - 1, true);
# Append the column to the end
} else {
$columns['review'] = __( 'Review', 'my_textdomain' );
}
return $columns;
}
////////////////////////////
# Make the Column sortable
////////////////////////////
add_filter( 'manage_edit-'.'review'.'_sortable_columns', 'sortable_column_review' );
function sortable_column_review( $columns ) {
$columns['review'] = 'review'; // unset($columns['review']); - to make unsortable
return $columns;
}
////////////////////////////////
# Filter sortable column query
////////////////////////////////
add_filter('pre_get_posts', 'sort_column_review');
function sort_column_review($query) {
if(!is_admin()) return;
$orderby = $query->get('orderby');
if($orderby == 'review') {
$field_key = 'review';
$query->set('meta_key', $field_key);
// $query->set('orderby', 'meta_value_num'); // if value is numeric
$query->set('orderby', 'meta_value');
}
return $query;
}
////////////////////////////
# Display the column value
////////////////////////////
add_action( 'manage_'.'review'.'_posts_custom_column' , 'display_column_review', 10, 2 );
function display_column_review( $column, $post_id ) {
switch($column) {
case 'review' :
$field_key = 'review';
echo get_post_meta( $post_id , $field_key, true );
break;
}
}
///////////////////////////////
# V. QUICK EDIT FIELDS
///////////////////////////////
//////////////////////////
# Add Quick Edit Field
//////////////////////////
// add_action('bulk_edit_custom_box', 'quick_edit_custom_review', 10, 2);
add_action('quick_edit_custom_box', 'quick_edit_custom_review', 10, 2);
function quick_edit_custom_review( $column, $post_type ) {
# Verify the post type
$acceptable_post_types = array('review');
if( !in_array($post_type, $acceptable_post_types) ) return false;
# Only display on the appropriate column name
switch($column){
case 'review' :
# Grab the metabox value
$field_key = 'review';
$value = get_post_meta( $post->ID, $field_key, true );
?>
<fieldset class="inline-edit-col-left">
<div class="inline-edit-col">
<div class="inline-edit-group">
<label>
<span class="title"><?php _e('Review'); ?></span>
<span class="input-text-wrap">
<input type="text" id="<?php echo $field_key; ?>" name="<?php echo $field_key; ?>" value="<?php echo esc_attr( $value ); ?>" size="25" maxlength="5" />
<?php
# Add an nonce field so we can verify the submission later.
$nonce_key = $field_key . '_nonce';
$nonce_string = 'review';
wp_nonce_field( $nonce_string, $nonce_key );
?>
</span><!-- .input-text-wrap -->
</label>
</div><!-- .inline-edit-group -->
</div><!-- .inline-edit-col -->
</fieldset>
<?php
break;
}
}
//////////////////////////
# Get Quick Edit Value
//////////////////////////
add_action('wp_ajax_nopriv_'.'quick_edit_get_review', 'quick_edit_get_review');
add_action('wp_ajax_'.'quick_edit_get_review', 'quick_edit_get_review');
function quick_edit_get_review($save = false){
# Grab the parameters
$post_id = $_REQUEST['post_id'];
$value = $_REQUEST['value'];
$nonce = $_REQUEST['nonce'];
$field_key = 'review';
# Verify nonce
$nonce_key = $field_key . '_nonce';
$nonce_string = 'review';
if( !isset( $nonce ) || !wp_verify_nonce( $nonce, $nonce_string ) ) {
# Display the JSON Error
header("Content-Type: application/json");
$results = array('status' => 'error', 'message' => __('Invalid submit key.'));
echo json_encode($results);
exit();
}
# Save the Data
if($save == true){
update_post_meta( $post_id , $field_key, $value );
$meta_value = $value;
# Retrieve the Data
} else {
$meta_value = get_post_meta( $post_id , $field_key, true );
}
# Display the JSON Results
header("Content-Type: application/json");
$results = array('status' => 'success', 'value' => $meta_value);
echo json_encode($results);
exit();
}
//////////////////////////
# Save Quick Edit Value
//////////////////////////
add_action('wp_ajax_nopriv_'.'quick_edit_save_review', 'quick_edit_save_review');
add_action('wp_ajax_'.'quick_edit_save_review', 'quick_edit_save_review');
function quick_edit_save_review(){
return quick_edit_get_review($save = true);
}
//////////////////////////
# Add Quick Edit Script
//////////////////////////
add_action('admin_footer-edit.php', 'quick_edit_script_review', 9999);
function quick_edit_script_review() {
# Verify the post type
$post_type = $_REQUEST['post_type'];
$acceptable_post_types = array('review');
if( !in_array($post_type, $acceptable_post_types) ) return false;
# Set the field key
$field_key = 'review';
$column_name = 'review';
$action1 = 'quick_edit_get_review';
$action2 = 'quick_edit_save_review';
?>
<script type="text/javascript">
jQuery(document).ready(function($){
// revert Quick Edit menu so that it refreshes properly
inlineEditPost.revert();
// On Row actions display
$(document).on('mouseup', '.row-actions .inline', function(e){
// Set the parameters
var _field_key = '<?php echo $field_key; ?>';
var _column_name = '<?php echo $column_name; ?>';
var _action1 = '<?php echo $action1; ?>';
var _action2 = '<?php echo $action2; ?>';
// Grab the post id
var $tr = $(this).closest('tr');
var _post_id = $tr.attr('id');
_post_id = (_post_id.indexOf('-') > -1) ? _post_id.split('-')[1] : _post_id;
setTimeout(function(){
$('#edit-'+_post_id).not('.edit-row-binded').each(function(){
var $edit_row = $(this).addClass('edit-row-binded');
var $input = $edit_row.find('[name="'+_field_key+'"]');
var _nonce = $input.siblings('[name="'+_field_key+'_nonce"]').val();
// Grab the original value
if(!$input.hasClass('valued')){
$.ajax({
url: ajaxurl, // this is a variable that WordPress has already defined for us
type: 'POST',
data: {
action : _action1,
nonce : _nonce,
post_id : _post_id
},
success : function(response, textStatus, jqXHR){
if(response.status == 'success'){
$input.addClass('valued').val( response.value ); // Update the value
}
}
});
}
// Update the value
$edit_row.on('mouseup', '.submit .save', function(){
var _new_val = $input.val();
$.ajax({
url: ajaxurl, // this is a variable that WordPress has already defined for us
type: 'POST',
data: {
action : _action2,
nonce : _nonce,
post_id : _post_id,
value : _new_val
},
success : function(response, textStatus, jqXHR){
if(response.status == 'success'){
setTimeout(function(){
$tr.find('td.'+_column_name).html( _new_val );
});
}
}
});
});
});
});
});
});
</script>
<?php
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment