i'm searching for a way to display the modified date of a custom field / meta box. until now, i only know how to echo
the_modified_date('l, j.n.Y');
but this one only works with the entire post.
i'am using a meta_box for additional pdf files uploading, code:
<?php class PDF_Metabox_id1 {
function __construct() {
add_action( 'post_mime_types', array( $this, 'pdf_mime_type_id1' ) );
add_action( 'add_meta_boxes', array( $this, 'admin_scripts_id1' ), 5 );
add_action( 'add_meta_boxes', array( $this, 'metabox_add_id1' ) );
add_action( 'save_post', array( $this, 'pdf_save_postdata_id1') );
add_action( 'wp_ajax_refresh_pdf', array( $this, 'refresh_pdf_id1' ) ); }
function pdf_mime_type_id1() {
$post_mime_types['application/pdf'] = array( __( 'PDFs' ), __( 'Manage PDFs' ), _n_noop( 'PDF <span class="count">(%s)</span>', 'PDFs <span class="count">(%s)</span>' ) );
return $post_mime_types;
}
function admin_scripts_id1() {
wp_register_script( 'pdf_metabox_js', get_stylesheet_directory_uri() . '/js/pdf_metabox.js' );
}
function metabox_add_id1() {
$post_types = array( 'myposttype','anotherposttype' );
$context = 'normal'; $priority = 'low';
foreach( $post_types as $post_type ) {
add_meta_box( 'pdf_metabox_id1', __( 'PDF Box 1', 'pdf_metabox_id1' ), array( $this, 'pdf_metabox_id1' ), $post_type, $context, $priority );
wp_enqueue_media();
wp_enqueue_script( 'pdf_metabox_js' );
}
}
function pdf_metabox_id1( $post ) {
$original_post = $post; echo $this->pdf_metabox_html_id1( $post->ID ); $post = $original_post;
}
function pdf_item_id1( $id ) {
if(!$id) return; $pdf_url = esc_url_raw(wp_get_attachment_url($id)); $pdf = $pdf_url; return $pdf;
}
function pdf_metabox_html_id1( $post_id ) {
$current_value = ''; $post_meta = get_post_custom($post_id);
if( isset($post_meta['pdf_id_id1'][0] ) ) $current_value = $post_meta['pdf_id_id1'][0];
$return = ''; wp_nonce_field( plugin_basename( __FILE__ ), 'pdf_noncename' );
$return .= '<p>';
$return .= '<a title="'.__( 'PDF', 'pdf_metabox_id1' ).'" class="button button-primary insert-pdf-button" id="insert_pdf_button_id1" href="#" style="float:left">'.__( 'Upload / editiere PDF', 'pdf_metabox_id1' ).'</a><span id="pdf_spinner_id1" class="spinner" style="float:left"></span></p>';
$return .= '<div style="clear:both"></div>';
$return .= '<input type="hidden" name="pdf_id_id1" id="pdf_id_id1" value="'.$current_value.'">';
$return .= '<div style="clear:both"></div>';
$return .= '<div id="pdf_wrapper_id1">';
$pdf = $this->pdf_item_id1( $current_value ); if( empty( $pdf ) ) {
$return .= '<p>Diesem Feld ist kein PDF hinterlegt.</p>'; } else {
$return .= '<br />URL des PDF:<br /> ';
$return .= $pdf; }
$return .= '</div>';
return $return;
}
function pdf_save_postdata_id1($post_id){
if ( isset($_POST['post_type']) && 'post' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_post', $post_id ) ) return; } if ( !isset( $_POST['pdf_noncename'] ) || ! wp_verify_nonce( $_POST['pdf_noncename'], plugin_basename( __FILE__ ) ) ) return;
if(isset($_POST['pdf_id_id1']) ): update_post_meta($post_id, 'pdf_id_id1', sanitize_text_field( $_POST['pdf_id_id1'] ) );
else: if (isset($post_id)) {
delete_post_meta($post_id, 'pdf_id_id1'); }
endif;
}
function refresh_pdf_id1() {
if(isset($_POST['id'])){
$item = $_POST['id'];
if($item != '' && $item !=0){
$pdf = $this->pdf_item_id1( $item );
$ret = array();
if( !empty( $pdf ) ) {$ret['success'] = true;
$ret['pdf'] = $pdf; } else {
$ret['success'] = false; } } else {
$ret['success'] = true; $ret['pdf'] = ''; } } else {
$ret['success'] = false; } echo json_encode( $ret ); die();
}
}
$PDF_Metabox_id1 = new PDF_Metabox_id1();
in my theme i'm using:
$post_meta_id1 = get_post_custom(get_the_ID());
$pdf_id_id1 = $post_meta_id1['pdf_id_id1'][0];
$pdf_url_id1 = wp_get_attachment_url($pdf_id_id1);
...and now i want to display the modified date of this field. any ideas?
As per the comment
how do i save the modified date of this custom field and how do i get it?
You may need to check every custom field in loop one by one if any of custom fields doesnot matched with the current post data then save a new custom field to post_meta. then retrieve in your template/page.
Just an idea:
<?php
function attributes_save_postdata( $post_id ) {
$postcustom = get_post_custom( $post_id );
$is_modified = false;
foreach ( $postcustom as $key => $val ) {
var_dump( $val );
// check your post custom values and
$getpostmeta = get_post_meta( $post_id, 'your_meta_key', true );
// if database value ($getpostmeta) not equal to current post value($_POST['your_meta_key'])
if ( $getpostmeta != $_POST['your_meta_key'] ) {
$is_modified = true;
// if found any custom field updated set $modified = true
}
}
// if found any custom field updated add or update new date and time
if ( $is_modified ) {
$date = date( 'Y-m-d h:i:s' ); // example : 2016-02-02 12:00:00 current date and time
update_post_meta( $post_id, '_modifieddate', $date );
}
}
add_action( 'save_post', 'attributes_save_postdata' );
Then in your theme. get modified date.
$post_id = get_the_ID();
$getpostmeta = get_post_meta( $post_id, 'your_meta_key', true );
I think that wordpress built-in function about this would help you out even for the custom fields.
<p>Last modified: <?php the_modified_time(); ?></p>
Related
If I need to add simply text input, I can use a function like woocommerce_wp_text_input inside (for eg.) woocommerce_product_options_advanced. Then I use woocommerce_process_product_meta where I can use update_post_meta. This is clear and handy!
Now - I would like to add a custom field with the PDF upload option as I would like to attach PDF files to the product.
So is it possible to add such a field in a similar way?
Note: This is NOT a virtual download product. It's just simple product.
You can add a custom meta boxes to upload a pdf. You can retrieve it by using <?php get_post_meta( get_the_ID(), 'advanced_options_pdf', true ); ?> on the front end. Just paste the following on your function.php file.
class Advanced_Options {
private $config = '{"title":"Advanced Options","prefix":"advanced_options_","domain":"advanced-options","class_name":"Advanced_Options","post-type":["product"],"context":"normal","priority":"default","fields":[{"type":"media","label":"PDF","return":"url","id":"advanced_options_pdf"}]}';
public function __construct() {
$this->config = json_decode( $this->config, true );
add_action( 'add_meta_boxes', [ $this, 'add_meta_boxes' ] );
add_action( 'admin_enqueue_scripts', [ $this, 'admin_enqueue_scripts' ] );
add_action( 'admin_head', [ $this, 'admin_head' ] );
add_action( 'save_post', [ $this, 'save_post' ] );
}
public function add_meta_boxes() {
foreach ( $this->config['post-type'] as $screen ) {
add_meta_box(
sanitize_title( $this->config['title'] ),
$this->config['title'],
[ $this, 'add_meta_box_callback' ],
$screen,
$this->config['context'],
$this->config['priority']
);
}
}
public function admin_enqueue_scripts() {
global $typenow;
if ( in_array( $typenow, $this->config['post-type'] ) ) {
wp_enqueue_media();
}
}
public function admin_head() {
global $typenow;
if ( in_array( $typenow, $this->config['post-type'] ) ) {
?><script>
jQuery.noConflict();
(function($) {
$(function() {
$('body').on('click', '.rwp-media-toggle', function(e) {
e.preventDefault();
let button = $(this);
let rwpMediaUploader = null;
rwpMediaUploader = wp.media({
title: button.data('modal-title'),
button: {
text: button.data('modal-button')
},
multiple: true
}).on('select', function() {
let attachment = rwpMediaUploader.state().get('selection').first().toJSON();
button.prev().val(attachment[button.data('return')]);
}).open();
});
});
})(jQuery);
</script><?php
}
}
public function save_post( $post_id ) {
foreach ( $this->config['fields'] as $field ) {
switch ( $field['type'] ) {
default:
if ( isset( $_POST[ $field['id'] ] ) ) {
$sanitized = sanitize_text_field( $_POST[ $field['id'] ] );
update_post_meta( $post_id, $field['id'], $sanitized );
}
}
}
}
public function add_meta_box_callback() {
$this->fields_table();
}
private function fields_table() {
?><table class="form-table" role="presentation">
<tbody><?php
foreach ( $this->config['fields'] as $field ) {
?><tr>
<th scope="row"><?php $this->label( $field ); ?></th>
<td><?php $this->field( $field ); ?></td>
</tr><?php
}
?></tbody>
</table><?php
}
private function label( $field ) {
switch ( $field['type'] ) {
case 'media':
printf(
'<label class="" for="%s_button">%s</label>',
$field['id'], $field['label']
);
break;
default:
printf(
'<label class="" for="%s">%s</label>',
$field['id'], $field['label']
);
}
}
private function field( $field ) {
switch ( $field['type'] ) {
case 'media':
$this->input( $field );
$this->media_button( $field );
break;
default:
$this->input( $field );
}
}
private function input( $field ) {
if ( $field['type'] === 'media' ) {
$field['type'] = 'text';
}
printf(
'<input class="regular-text %s" id="%s" name="%s" %s type="%s" value="%s">',
isset( $field['class'] ) ? $field['class'] : '',
$field['id'], $field['id'],
isset( $field['pattern'] ) ? "pattern='{$field['pattern']}'" : '',
$field['type'],
$this->value( $field )
);
}
private function media_button( $field ) {
printf(
' <button class="button rwp-media-toggle" data-modal-button="%s" data-modal-title="%s" data-return="%s" id="%s_button" name="%s_button" type="button">%s</button>',
isset( $field['modal-button'] ) ? $field['modal-button'] : __( 'Select this file', 'advanced-options' ),
isset( $field['modal-title'] ) ? $field['modal-title'] : __( 'Choose a file', 'advanced-options' ),
$field['return'],
$field['id'], $field['id'],
isset( $field['button-text'] ) ? $field['button-text'] : __( 'Upload', 'advanced-options' )
);
}
private function value( $field ) {
global $post;
if ( metadata_exists( 'post', $post->ID, $field['id'] ) ) {
$value = get_post_meta( $post->ID, $field['id'], true );
} else if ( isset( $field['default'] ) ) {
$value = $field['default'];
} else {
return '';
}
return str_replace( '\u0027', "'", $value );
}
}
new Advanced_Options;
Hello guys i got new WP theme and i cant install im getting this error on website
Parse error: syntax error, unexpected '}', expecting end of file in
/storage/h3/665/790665/public_html/wp-content/themes/gameaddict/post_templates.php
on line 1
<?php
class Single_Post_Template_Plugin {
function __construct() {
add_action( 'admin_menu', array( $this, 'add_metabox' ) );
add_action( 'save_post', array( $this, 'metabox_save' ), 1, 2 );
add_filter( 'single_template', array( $this, 'get_post_template' ) );
}
function get_post_template( $template ) {
global $post;
$custom_field = get_post_meta( $post->ID, '_wp_post_template', true );
if( !$custom_field )
return $template;
/** Prevent directory traversal */
$custom_field = str_replace( '..', '', $custom_field );
if( file_exists( get_stylesheet_directory() . "/{$custom_field}" ) )
$template = get_stylesheet_directory() . "/{$custom_field}";
elseif( file_exists( get_template_directory() . "/{$custom_field}" ) )
$template = get_template_directory() . "/{$custom_field}";
return $template;
}
function get_post_templates() {
$templates = wp_get_theme()->get_files( 'php', 1 );
$post_templates = array();
$base = array( trailingslashit( get_template_directory()), trailingslashit( get_stylesheet_directory()) );
foreach ( (array) $templates as $file => $full_path ) {
if( $full_path == get_theme_root().'/gameaddict/post_templates.php'){continue;}else{
if ( !preg_match( '|Single Post Template:(.*)$|mi', file_get_contents( $full_path ), $header ))
continue;
$post_templates[ $file ] = _cleanup_header_comment( $header[1] );
}}
return $post_templates;
}
function post_templates_dropdown() {
global $post;
$post_templates = $this->get_post_templates();
/** Loop through templates, make them options */
foreach ( (array) $post_templates as $template_file => $template_name ) {
$selected = ( $template_file == get_post_meta( $post->ID, '_wp_post_template', true ) ) ? ' selected="selected"' : '';
$opt = '<option value="' . esc_attr( $template_file ) . '"' . $selected . '>' . esc_html( $template_name ) . '</option>';
echo $opt;
}
}
function add_metabox() {
$screens = array( 'post', 'portfolio' );
foreach ( $screens as $screen ) {
add_meta_box(
'pt_post_templates',
__( 'Sidebar position', 'addict' ),
array( $this, 'metabox' ),
$screen,'normal', 'high'
);
}
}
function metabox( $post ) {
?>
<input type="hidden" name="pt_noncename" id="pt_noncename" value="<?php echo wp_create_nonce( plugin_basename( __FILE__ ) ); ?>" />
<label class="hidden" for="post_template"><?php _e( 'Post Template', 'addict' ); ?></label><br />
<select name="_wp_post_template" id="post_template" class="dropdown">
<?php $this->post_templates_dropdown(); ?>
</select>
<?php
}
function metabox_save( $post_id, $post ) {
/*
* Verify this came from the our screen and with proper authorization,
* because save_post can be triggered at other times
*/
if(isset($_POST['pt_noncename'])){
if ( !wp_verify_nonce( $_POST['pt_noncename'], plugin_basename( __FILE__ ) ) )
return $post->ID;
}
/** Is the user allowed to edit the post or page? */
if(isset($_POST['post_type'])){
if ( 'page' == $_POST['post_type'] )
if ( !current_user_can( 'edit_page', $post->ID ) )
return $post->ID;
else
if ( !current_user_can( 'edit_post', $post->ID ) )
return $post->ID;
}
/** OK, we're authenticated: we need to find and save the data */
/** Put the data into an array to make it easier to loop though and save */
if(isset($_POST['_wp_post_template'])){
$mydata['_wp_post_template'] = $_POST['_wp_post_template'];
}
/** Add values of $mydata as custom fields */
if(isset($mydata)){
foreach ( $mydata as $key => $value ) {
/** Don't store custom data twice */
if( 'revision' == $post->post_type )
return;
/** If $value is an array, make it a CSV (unlikely) */
$value = implode( ',', (array) $value );
/** Update the data if it exists, or add it if it doesn't */
if( get_post_meta( $post->ID, $key, false ) )
update_post_meta( $post->ID, $key, $value );
else
add_post_meta( $post->ID, $key, $value );
/** Delete if blank */
if( !$value )
delete_post_meta( $post->ID, $key );
}}
}
}
add_action( 'init', 'post_templates_plugin_init' );
/**
* Instantiate the class after theme has been set up.
*/
function post_templates_plugin_init() {
new Single_Post_Template_Plugin;
}
Assuming the theme is this one https://themeforest.net/item/game-addict-clan-war-gaming-theme/6771881 and it's purchased from themeforest, it should work right out of the box. Try downloading it again, make sure to check if there is not a zipped file inside of the zip you are downloading to make sure you are uploading the right file, sometimes the zip you download has a lot of files like documentation and demos, but the actual theme file is another zip inside.
If nothing of the above helps, write to their customer support.
Basically, it's complaining that wp-content/themes/gameaddict/post_templates.php has a } on line 1, while PHP was expecting end of a file. The code you've included seems fine. The issue is most likely about the developer closing a bracket without opening it, somewhere in the code. It seems like you're using a pre-made theme, in that case contacting the developer would be the best option.
I have this following code to give a textarea to a front end user to use it as notes on a page to write things to remember. But this code saves only one sticky note that can be edited whenever the user wants. My questions is if there is a way to save the content somewhere and have a new one every time submit is pressed. or a add new sticky button.
require_once( plugin_dir_path( __FILE__ ) . 'wp-ajax.php' );
class notepad_stikey extends WP_Ajax {
var $user;
var $username;
function __construct() {
parent::__construct();
add_action('init', array( &$this, 'setup') );
}
function setup() {
$this->user = get_current_user_id();
$this->username = get_userdata( $this->user )->user_login;
$this->notes = get_user_meta( $this->user, 'notepad_stikey', true );
$this->ph = ' '; //placeholder
if (empty( $this->notes )) {
$this->notes = $this->ph;
}
add_action('wp_enqueue_scripts', array( &$this, 'scripts') );
}
function scripts() {
wp_enqueue_script( 'notepad_stikey', plugins_url( 'notepad_stikey.js', __FILE__ ), array( 'jquery' ) );
wp_localize_script( 'notepad_stikey', 'notepad_stikey', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
function an_change_notepad_stikey() {
$notes = trim( $_POST['notes'] );
//if notes is empty, delete
if ( empty($notes) ) {
if ( delete_user_meta( $this->user, 'notepad_stikey' ) )
die( 'notes deleted' );
}
//notes are the same, notes = placeholder, or resaving empty notes
if ( $notes == $this->notes || $notes == $this->ph || ( empty($notes) && $this->notes == $this->ph) )
die();
//update
if ( update_user_meta( $this->user, 'notepad_stikey', $notes ) )
die( 'updated' );
//hopefully, we don't get this far. if we do, something is wrong
die( 'uh oh. notes could not be saved' );
}
}
global $notepad_stikey;
$notepad_stikey = new notepad_stikey();
add_action( 'widgets_init', 'notepad_stikey_load' );
function notepad_stikey_load() {
register_widget( 'notepad_stikey_Widget' );
}
class notepad_stikey_Widget extends WP_Widget {
function notepad_stikey_Widget() {
$widget_ops = array('classname' => 'notepad_stikey', 'description' => __( 'notepad_stikey. Only one instance please. Else this will break.', 'notepad_stikey' ) );
$control_ops = array( 'id_base' => 'notepad_stikey' );
parent::WP_Widget( 'notepad_stikey', __( 'notepad_stikey', 'notepad_stikey' ), $widget_ops, $control_ops );
}
function widget( $args, $instance ) {
extract( $args, EXTR_SKIP );
echo $before_widget;
global $notepad_stikey;
$username = $notepad_stikey->username;
$notes = $notepad_stikey->notes;
//overwrite title
$instance['title'] = 'Notepad for '. $username;
echo $instance['hide_title'] ? '' : $before_title . $instance['title'] . $after_title;
echo "<div id='notepad_stikey' class='$username' style='border: 1px solid #eee; padding: 10px 15px;min-height: 100px;'>";
echo $notes;
echo '</div><span style="float:left;color:#008;" id="notepad_stikey_response"></span><small style="float:right;">click box above to edit</small>';
echo $after_widget;
} //end widget()
function update($new_instance, $old_instance) {
$instance = $old_instance;
$instance['title'] = esc_attr( $new_instance['title'] );
$instance['hide_title'] = (bool) $new_instance['hide_title'] ? 1 : 0;
return $instance;
} //end update()
function form( $instance ) {
$instance = wp_parse_args( (array) $instance, array( 'hide_title' => 0 ) );
extract( $instance );
?>
<p>
<input type="checkbox" class="checkbox" id="<?php echo $this->get_field_id('hide_title'); ?>" name="<?php echo $this->get_field_name('hide_title'); ?>"<?php checked( $hide_title ); ?> />
<label for="<?php echo $this->get_field_id('hide_title'); ?>"><?php _e('Hide Title?', 'notepad_stikey' );?></label>
</p>
<?php
} //end form()
}
if (!class_exists('WP_Ajax')) {
class WP_Ajax {
function __construct( $ajax_prefix = 'a', $nopriv_prefix = 'n' ) {
$regex = "/^($ajax_prefix)?($nopriv_prefix)?_|^($nopriv_prefix)? ($ajax_prefix)?_/";
$methods = get_class_methods( $this );
foreach ( $methods as $method ) {
if ( preg_match( $regex, $method, $matches ) ) {
if ( count( $matches ) > 1 ) {
$action = preg_replace( $regex, '', $method );
if ( count( $matches ) == 3 ) {
add_action( "wp_ajax_$action", array( $this, $method ) );
add_action( "wp_ajax_nopriv_$action", array( $this, $method ) );
} else {
if ( $matches[1] == $ajax_prefix ) {
add_action( "wp_ajax_$action", array( $this, $method ) );
} else {
add_action( "wp_ajax_nopriv_$action", array( $this, $method ) );
}
}
}
}
}
}
}
}
jQuery(document).ready(function($) {
$('#notepad_stikey').click(function(e) {
tag = e.target.tagName;
if ( tag != 'TEXTAREA' && tag != 'INPUT' ) {
contents = $(this).html();
$(this).html( '<textarea rows="5" cols="50" style="display:block;width:98%;height:100px;">' + contents + '</textarea><input type="submit" class="save" style="position:relative;z-index:99" />' );
}
});
$('#notepad_stikey input.save').live( 'click', function() {
new_contents = $(this).siblings('textarea').val();
$('#notepad_stikey').html( new_contents );
change_notepad_stikey( new_contents );
return false;
});
function change_notepad_stikey( notes ) {
$('#notepad_stikey_response').text( '...' );
$.post(notepad_stikey.ajaxurl,
{
'action' : 'change_notepad_stikey',
'notes' : notes
}, function(response) {
//if (response != '') {
//alert( response );
$('#notepad_stikey_response').text( response );
//}
}, 'text' );
}
});
I want to change text of published under date column of post list in wordpress.
see below image
You can try using following way.
<?php
function my_custom_columns( $columns ) {
unset( $columns['date'] );
$columns['mydate'] = 'My Custom Date';
return $columns;
}
function my_format_column( $column_name , $post_id ) {
if($column_name == 'mydate'){
echo get_the_time( 'l, F j, Y', $post_id )."<br>".get_post_status( $post_id );
}
}
function my_column_register_sortable( $columns ) {
$columns['mydate'] = 'mydate';
return $columns;
}
function my_column_orderby( $vars ) {
if ( isset( $vars['orderby'] ) && 'mydate' == $vars['orderby'] ) {
$vars = array_merge( $vars, array(
'orderby' => 'date'
) );
}
return $vars;
}
function my_column_init() {
add_filter( 'manage_posts_columns' , 'my_custom_columns' );
add_action( 'manage_posts_custom_column' , 'my_format_column' , 10 , 2 );
add_filter( 'manage_edit-post_sortable_columns', 'my_column_register_sortable' );
add_filter( 'request', 'my_column_orderby' );
}
add_action( 'admin_init' , 'my_column_init' );
?>
I got a WordPress Rating plugin from "http://www.smashingmagazine.com/2012/05/08/adding-custom-fields-in-wordpress-comment-form/"
I would like to count the total number of rating and print that number under the Blog Post. Is this possible?
I added some customisation in this code.
<?php
// Add fields after default fields above the comment box, always visible
add_action( 'comment_form_logged_in_after', 'additional_fields' );
add_action( 'comment_form_after_fields', 'additional_fields' );
function additional_fields () {
echo '<p class="comment-form-rating">'.
'<label for="rating">'. __('Rating') . '<span class="required">*</span></label>
<span class="commentratingbox">';
for( $i=1; $i <= 5; $i++ )
echo '<span class="commentrating"><input type="radio" checked name="rating" id="rating" value="'. $i .'"/>'. $i .' Star</span>';
echo'</span></p>';
}
// Save the comment meta data along with comment
add_action( 'comment_post', 'save_comment_meta_data' );
function save_comment_meta_data( $comment_id ) {
if ( ( isset( $_POST['rating'] ) ) && ( $_POST['rating'] != '') )
$rating = wp_filter_nohtml_kses($_POST['rating']);
add_comment_meta( $comment_id, 'rating', $rating );
}
// Add the filter to check if the comment meta data has been filled or not
add_filter( 'preprocess_comment', 'verify_comment_meta_data' );
function verify_comment_meta_data( $commentdata ) {
if ( ! isset( $_POST['rating'] ) )
wp_die( __( 'Error: You did not add your rating. Hit the BACK button of your Web browser and resubmit your comment with rating.' ) );
return $commentdata;
}
//Add an edit option in comment edit screen
add_action( 'add_meta_boxes_comment', 'extend_comment_add_meta_box' );
function extend_comment_add_meta_box() {
add_meta_box( 'title', __( 'Comment Metadata - Extend Comment' ), 'extend_comment_meta_box', 'comment', 'normal', 'high' );
}
function extend_comment_meta_box ( $comment ) {
$phone = get_comment_meta( $comment->comment_ID, 'phone', true );
$title = get_comment_meta( $comment->comment_ID, 'title', true );
$rating = get_comment_meta( $comment->comment_ID, 'rating', true );
wp_nonce_field( 'extend_comment_update', 'extend_comment_update', false );
?>
<p>
<label for="rating"><?php _e( 'Rating: ' ); ?></label>
<span class="commentratingbox">
<?php for( $i=1; $i <= 5; $i++ ) {
echo '<span class="commentrating"><input type="radio" name="rating" id="rating" value="'. $i .'"';
if ( $rating == $i ) echo ' checked="checked"';
echo ' />'. $i .' </span>';
}
?>
</span>
</p>
<?php
}
// Update comment meta data from comment edit screen
add_action( 'edit_comment', 'extend_comment_edit_metafields' );
function extend_comment_edit_metafields( $comment_id ) {
if( ! isset( $_POST['extend_comment_update'] ) || ! wp_verify_nonce( $_POST['extend_comment_update'], 'extend_comment_update' ) ) return;
if ( ( isset( $_POST['phone'] ) ) && ( $_POST['phone'] != '') ) :
$phone = wp_filter_nohtml_kses($_POST['phone']);
update_comment_meta( $comment_id, 'phone', $phone );
else :
delete_comment_meta( $comment_id, 'phone');
endif;
if ( ( isset( $_POST['title'] ) ) && ( $_POST['title'] != '') ):
$title = wp_filter_nohtml_kses($_POST['title']);
update_comment_meta( $comment_id, 'title', $title );
else :
delete_comment_meta( $comment_id, 'title');
endif;
if ( ( isset( $_POST['rating'] ) ) && ( $_POST['rating'] != '') ):
$rating = wp_filter_nohtml_kses($_POST['rating']);
update_comment_meta( $comment_id, 'rating', $rating );
else :
delete_comment_meta( $comment_id, 'rating');
endif;
}
// Add the comment meta (saved earlier) to the comment text
// You can also output the comment meta values directly in comments template
add_filter( 'comment_text', 'modify_comment');
function modify_comment( $text ){
$plugin_url_path = WP_PLUGIN_URL;
if( $commenttitle = get_comment_meta( get_comment_ID(), 'title', true ) ) {
$commenttitle = '<strong>' . esc_attr( $commenttitle ) . '</strong><br/>';
$text = $commenttitle . $text;
}
if( $commentrating = get_comment_meta( get_comment_ID(), 'rating', true ) ) {
$commentrating = '<p class="comment-rating"> <img src="'. $plugin_url_path .
'/ExtendComment/images/'. $commentrating . 'star.gif"/><br/>Rating: <strong>'. $commentrating .' / 5</strong></p>';
$text = $text . $commentrating;
return $text;
} else {
return $text;
}
}
It would go something like this. Appending the total for all ratings:
if( !is_admin() )
add_filter( 'the_content', 'content_so_23778986' );
function content_so_23778986( $content )
{
if( !is_single() )
return $content;
# Get all comments from current post
$comms = get_comments( array( 'post_id'=>get_the_ID() ) );
$counter = null;
if( $comms )
{
$total = count( $comms );
# Iterate all comments and add its rating to the counter
foreach( $comms as $c )
{
$rating = (int) get_comment_meta( $c->comment_ID, 'rating', true );
$counter += $rating;
}
# Calculate and print the totals
$counter = '<br />' . $counter / $total . ' de 5';
}
return $content . $counter;
}