Skip to content

Instantly share code, notes, and snippets.

@geilt
Last active December 12, 2015 12:38
Show Gist options
  • Save geilt/4772859 to your computer and use it in GitHub Desktop.
Save geilt/4772859 to your computer and use it in GitHub Desktop.
Simpul Meta - For Adding Meta Fields to Wordpress Post Types
<?php
/**
* SimpulMeta by Alexander Conroy
* Copyright 2012 Esotech Inc.
* MIT License
* http://opensource.org/licenses/MIT
*
* args = array()
* Valid Values:
* post_type - Which post type to attach meta to.
* child_of - Makes sure this only shows on the child of a specific page id
* fields = array()
* fieldname => fieldtype
* Valid Types: text, image, file, textarea, checkbox, date, datetime, select
* fields_values = array()
* value => label
* simpul.meta.upload is Included in a function now and no longer needs to be included
*/
$page_meta_args =
array(
'post_type' => 'page',
'child_of' => 5453,
'fields' => array(
'field1' => 'select',
'field2' => 'file'
),
'fields_values' => array('field1'
=> array('value1' => 'label1',
'value2' => 'label2')
)
);
$page_meta = new SimpulMeta( $page_meta_args );
class SimpulMeta {
public function __construct( $args ) {
$this->post_type = $args['post_type'];
$this->fields = $args['fields'];
$this->fields_values = !empty($args['fields_values']) ? $args['fields_values'] : '';
$this->child_of = !empty($args['child_of']) ? $args['child_of'] : '';
self::setMetaFields();
add_action( 'add_meta_boxes', array(&$this, 'addCustomBox') ); // Add Meta Box
add_action( 'save_post', array(&$this, 'savePostData') ); // Save Meta Box Info
}
public function setMetaFields()
{
foreach($this->fields as $key => $value):
$this->meta_fields[$this->meta_prefix . $key] = $value;
endforeach;
//Iterate and Create Label.
foreach($this->meta_fields as $field => $format):
$this->meta_box_fields[$field] = self::getLabel(str_replace($this->meta_prefix, "", $field));
$this->meta_box_fields_formats[$field] = $format;
endforeach;
}
public function addCustomBox() {
global $post;
if((!empty($this->child_of) && $this->child_of == $post->post_parent)
|| empty($this->child_of)):
add_meta_box(
$this->post_type . '_meta',
__( self::getLabel($this->post_type) . ' Meta', $this->post_type . '_meta' ),
array(&$this, 'innerCustomBox'),
$this->post_type,
'side',
'high'
);
if( $post->post_type == $this->post_type ): //These scripts interfere with regular post insertion =(
add_action('admin_print_scripts', array( &$this, 'registerScripts' ) );
add_action('admin_head', array( $this, 'simpulMetaUpload' ), 11);
add_action('admin_print_styles' , array( &$this, 'registerStyles' ) );
endif;
endif;
}
//Add the Inner Custom Meta Box and the custom Meta Fields
public function innerCustomBox( $post ) {
global $post;
// Use nonce for verification
wp_nonce_field( plugin_basename( __FILE__ ), 'myplugin_noncename' );
echo '<table class="widefat" cellpadding="0" cellspacing="0" border="0">';
//Add this to work with Custom Javascript that needs image dir.
echo '<span id="bloginfo" stylesheet_dir_uri="' . get_template_directory_uri() . '" style="display: none">';
// The actual fields for data entry
//Iterate through the array. Will expand or contract as fields are added in the database (through scraper).
foreach($this->meta_box_fields as $field => $label):
echo self::formatFields($post, $field, $label, $this->post_type . '_meta', $this->meta_box_fields_formats[$field] );
endforeach;
echo "</table>";
}
//Saves the Meta Box Values
public function savePostData( $post_id ) {
global $post;
// verify if this is an auto save routine.
// If it is our form has not been submitted, so we dont want to do anything
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
// verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
// Check permissions
if ( !current_user_can( 'edit_post', $post->ID) )
return;
// OK, we're authenticated: we need to find and save the data
foreach($this->meta_box_fields_formats as $field => $format):
if($_POST[$field]):
switch( $format ):
case "datetime":
update_post_meta($post->ID, $field, date("Y-m-d H:i:s", strtotime( $_POST[$field] ) ) );
break;
case "date":
update_post_meta($post->ID, $field, date("Y-m-d", strtotime( $_POST[$field] ) ) );
break;
default:
update_post_meta($post->ID, $field, $_POST[$field]);
break;
endswitch;
else:
if( get_post_meta($post->ID, $field, true) ):
delete_post_meta($post->ID, $field); // Useful for Checkboxes. Delete completely.
endif;
endif;
endforeach;;
// Do something with $mydata
// probably using add_post_meta(), update_post_meta(), or
// a custom table (see Further Reading section below)
}
public function formatFields($post, $field_name, $label, $box, $format )
{
echo "<tr>";
switch($format):
case "datetime":
echo '<th><label for="' . $field_name . '">';
_e($label, $box );
echo '</label> </th>';
echo '<td><input type="text" id="' . $field_name . '" name="' . $field_name . '" class="hasDateTimePicker" value="' . get_post_meta($post->ID, $field_name ,true) . '" /></td>';
break;
case "date":
echo '<th><label for="' . $field_name . '">';
_e($label, $box );
echo '</label> </th>';
echo '<td><input type="text" id="' . $field_name . '" name="' . $field_name . '" class="hasDatePicker" value="' . get_post_meta($post->ID, $field_name ,true) . '" /></td>';
break;
case "image":
echo '<th colspan="2"><label for="' . $field_name . '">';
_e($label, $box );
echo '</label><br>';
echo '
<input id="simpul_meta_upload_' . $field_name . '" class="regular-text" type="text" name="' . $field_name . '" value="' . get_post_meta($post->ID, $field_name ,true) . '" style="width: 70%; margin: 0;"/>
<button class="simpul_meta_upload button-secondary" data-input="simpul_meta_upload_' . $field_name . '" pe="button">Browse</button>';
$image = get_post_meta($post->ID, $field_name ,true);
if($image):
echo '<img src="' . $image . '" style="width: 100%; margin-top: 10px;" />';
endif;
echo "</th>";
break;
case "file":
echo '<th colspan="2"><label for="' . $field_name . '">';
_e($label, $box );
echo '</label><br>';
echo '
<input id="simpul_meta_upload_' . $field_name . '" class="regular-text" type="text" name="' . $field_name . '" value="' . get_post_meta($post->ID, $field_name ,true) . '" style="width: 70%; margin: 0;"/>
<button class="simpul_meta_upload button-secondary" data-input="simpul_meta_upload_' . $field_name . '" name="' . $field_name . '" type="button">Browse</button>';
echo "</th>";
break;
case "checkbox":
$value = get_post_meta($post->ID, $field_name ,true);
if($value) $checked = "checked"; else $checked = '';
echo '<th><label for="' . $field_name . '">';
_e($label, $box );
echo '</label><br>';
echo '<td><input type="checkbox" id="' . $field_name . '" name="' . $field_name . '" value="1" ' . $checked . ' /></td>';
break;
case "select":
if(!empty($this->fields_values[$field_name])):
$value = get_post_meta($post->ID, $field_name ,true);
if($value) $checked = "checked"; else $checked = '';
echo '<th><label for="' . $field_name . '">';
_e($label, $box );
echo '</label><br>';
echo '<td><select id="' . $field_name . '" name="' . $field_name . '" style="width: 100%;">';
foreach($this->fields_values[$field_name] as $key => $value):
echo '<option value="' . $key . '">' . $value . '</option>';
endforeach;
echo '</select></td>';
endif;
break;
case "textarea":
echo '<th colspan="2"><label for="' . $field_name . '">';
_e($label, $box );
echo '</label><br>';
echo '<textarea rows="4" style="width: 100%;" id="' . $field_name . '" name="' . $field_name . '">' . get_post_meta($post->ID, $field_name ,true) . '</textarea></th>';
break;
default:
echo '<th><label for="' . $field_name . '">';
_e($label, $box );
echo '<td><input type="text" id="' . $field_name . '" name="' . $field_name . '" value="' . get_post_meta($post->ID, $field_name ,true) . '" " style="width: 100%;"/></td>';
break;
endswitch;
echo "</tr>";
}
public function getLabel($key)
{
$glued = array();
if( strpos( $key, "-" ) ) $pieces = explode( "-", $key );
elseif( strpos( $key, "_" ) ) $pieces = explode( "_", $key );
else $pieces = explode(" ", $key);
foreach($pieces as $piece):
if($piece == "id"):
$glued[] = strtoupper($piece);
else:
$glued[] = ucfirst($piece);
endif;
endforeach;
return implode(" ", $glued);
}
public function registerScripts()
{
if(!wp_script_is('media-upload')):
wp_enqueue_script('media-upload');
endif;
if(!wp_script_is('thickbox')):
wp_enqueue_script('thickbox');
endif;
}
public function registerStyles()
{
wp_enqueue_style('thickbox');
//wp_register_style('jquery-ui-custom-css', WP_PLUGIN_URL . '/simpulevents/css/jquery-ui-1.8.16.custom.css');
//wp_enqueue_style('jquery-ui-custom-css');
}
public function simpulMetaUpload(){
$GLOBALS['simpul_meta_upload'] = true;
?>
<script type="text/javascript">
var original_send_to_editor = "";
var modified_send_to_editor = "";
var formfield = '';
var hrefurl = '';
jQuery(document).ready( function() {
original_send_to_editor = window.send_to_editor;
modified_send_to_editor = function(html) {
hrefurl = jQuery('img',html).attr('src');
console.log(jQuery(html));
if(!hrefurl) {
hrefurl = jQuery(html).attr('href'); // We do this to get Links like PDF's
}
hrefurl = hrefurl.substr(hrefurl.indexOf('/',8)); // Skips "https://" and extracts after first instance of "/" for relative URL, ex. "/wp-content/themes/currentheme/images/etc.jpg"
console.log(hrefurl);
jQuery('#' + formfield).val(hrefurl);
tb_remove();
window.send_to_editor = original_send_to_editor;
};
jQuery('.simpul_meta_upload').click(function() {
window.send_to_editor = modified_send_to_editor;
formfield = jQuery(this).attr('data-input');
tb_show('Add File', 'media-upload.php?TB_iframe=true');
console.log(formfield);
return false;
});
} );
</script>
<?php
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment