Save data from multiple checkbox metaboxes in Wordpress - php

I'm learning how to add metaboxes to posts. I would like to create a group of metaboxes with text inputs and multiple checboxes. For now the checkboxes are just put there like that, but eventually they will be generated by a foreach loop with content from another place, so it's important for me to give them names like entry[0], entry[1] and so on. They have to be saved by a loop as I will not know how many will be generated.
This is what I have so far:
// adding the metaboxes
function add_post_reference() {
add_meta_box('post-reference', 'Reference', 'referenceCallBack', 'languagecourses', 'side', 'high');
}
add_action('add_meta_boxes', 'add_post_reference');
// callback function
function referenceCallBack($post) {
wp_nonce_field( 'reference_meta_box', 'reference_nonce' );
$name_value = get_post_meta( $post->ID, '_post_reference_name', true );
$link_value = get_post_meta( $post->ID, '_post_reference_link', true );
trying to do the same as above with my checkboxes but I don't know what to put there:
$teachers_value = get_post_meta( $post->ID, 'what do I put here?', true ); // what do I put here?
Echoing the html structure now (the text inputs work (values get saved), I'm trying to figure out how to make the checkboxes save as well:
echo '<label for="reference-name">'. 'Reference Name' .'</label>';
echo '<input type="text" id="reference-name" name="post_reference_name" placeholder="Example" value="'.$name_value.'" size="25"/>';
echo '<p class="howto">'. 'Add the name of the reference' .'</p>';
echo '<label for="reference-link">'. 'Reference Link' .'</label>';
echo '<input type="text" id="reference-link" name="post_reference_link" placeholder="http://www.example.com/" value="'.$link_value.'" size="25"/>';
echo '<p class="howto">'. 'Add the link of the reference' .'</p>';
// my checkboxes
echo '<input type="checkbox" name="entry[0]" value="moredata">';
echo '<input type="checkbox" name="entry[1]" value="moredata">';
echo '<input type="checkbox" name="entry[2]" value="moredata">';
echo '<input type="checkbox" name="entry[3]" value="moredata">';
echo '<input type="checkbox" name="entry[4]" value="moredata">';
}
function save_post_reference( $post_id ) {
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
if ( ! isset( $_POST['reference_nonce'] ) ) {
return;
}
if ( ! wp_verify_nonce( $_POST['reference_nonce'], 'reference_meta_box' ) ) {
return;
}
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
if ( ! isset( $_POST['post_reference_name'] ) || ! isset( $_POST['post_reference_link'] ) ) {
return;
}
$reference_name = sanitize_text_field( $_POST['post_reference_name'] );
$reference_link = sanitize_text_field( $_POST['post_reference_link'] );
// looping through the checkboxes
for ($i = 0; $i < 5; $i++) {
$teachers_names = sanitize_text_field($_POST['entry'][$i]);
}
update_post_meta( $post_id, '_post_reference_name', $reference_name );
update_post_meta( $post_id, '_post_reference_link', $reference_link );
Again, what do I put here?
update_post_meta( $post_id, 'whatdoIputhere?', $teachers_names); // what do I put here?
}
add_action( 'save_post', 'save_post_reference' );
Could anybody please help me on that?

Your HTML code should be like :
echo '<input type="checkbox" name="entry[]" value="moredata">';
echo '<input type="checkbox" name="entry[]" value="moredata">';
echo '<input type="checkbox" name="entry[]" value="moredata">';
echo '<input type="checkbox" name="entry[]" value="moredata">';
echo '<input type="checkbox" name="entry[]" value="moredata">';
now you will save the data :
key = 'entry';
$values_to_save = array();
$new_values = $_POST['entry'];
$existing_values = get_post_meta( $post_id, $key, true ) ;
if(!empty($existing_values)){
foreach((array) $existing_values as $existing_value){
$values_to_save[] = $existing_value;
}
}
if(!empty($new_values)){
foreach((array) $new_values as $new_value ){
$values_to_save[] = $new_value ;
}
}
update_post_meta( $post_id, $key, $values_to_save );
Now to fetch the data use the below code :
$key = 'entry';
$values = get_post_meta( $post_id, $key, true );
foreach((array) $values as $value){
echo $value . '<br>';
}

Ok, I updated my functions with your code and this is how it looks now:
function add_post_reference() {
add_meta_box('post-reference', 'Reference', 'referenceCallBack', 'languagecourses', 'side', 'high');
}
add_action('add_meta_boxes', 'add_post_reference');
// callback
function referenceCallBack($post) {
wp_nonce_field( 'reference_meta_box', 'reference_nonce' );
$name_value = get_post_meta( $post->ID, '_post_reference_name', true );
$link_value = get_post_meta( $post->ID, '_post_reference_link', true );
$key = 'entry';
$values = get_post_meta( $post_id, $key, true );
foreach((array) $values as $value){
echo $value . '<br>';
}
echo '<label for="reference-name">'. 'Reference Name' .'</label>';
echo '<input type="text" id="reference-name" name="post_reference_name" placeholder="Example" value="'.$name_value.'" size="25"/>';
echo '<p class="howto">'. 'Add the name of the reference' .'</p>';
echo '<label for="reference-link">'. 'Reference Link' .'</label>';
echo '<input type="text" id="reference-link" name="post_reference_link" placeholder="http://www.example.com/" value="'.$link_value.'" size="25"/>';
echo '<p class="howto">'. 'Add the link of the reference' .'</p>';
echo '<input type="checkbox" name="entry[]" value="moredata">';
echo '<input type="checkbox" name="entry[]" value="moredata">';
echo '<input type="checkbox" name="entry[]" value="moredata">';
echo '<input type="checkbox" name="entry[]" value="moredata">';
echo '<input type="checkbox" name="entry[]" value="moredata">';
}
function save_post_reference( $post_id ) {
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
if ( ! isset( $_POST['reference_nonce'] ) ) {
return;
}
if ( ! wp_verify_nonce( $_POST['reference_nonce'], 'reference_meta_box' ) ) {
return;
}
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
if ( ! isset( $_POST['post_reference_name'] ) || ! isset( $_POST['post_reference_link'] ) ) {
return;
}
$reference_name = sanitize_text_field( $_POST['post_reference_name'] );
$reference_link = sanitize_text_field( $_POST['post_reference_link'] );
$key = 'entry';
$values_to_save = array();
$new_values = $_POST['entry'];
$existing_values = get_post_meta( $post_id, $key, true ) ;
if(!empty($existing_values)){
foreach((array) $existing_values as $existing_value){
$values_to_save[] = $existing_value;
}
}
if(!empty($new_values)){
foreach((array) $new_values as $new_value ){
$values_to_save[] = $new_value ;
}
}
update_post_meta( $post_id, $key, $values_to_save );
update_post_meta( $post_id, '_post_reference_name', $reference_name );
update_post_meta( $post_id, '_post_reference_link', $reference_link );
}
add_action( 'save_post', 'save_post_reference' );
One thing I change was that key = to $key = as otherwise it was throwing an error.
And still - no change... one thing I thought about is that maybe it does save the data, but the checkboxes remain unchecked?

Related

How to add custom field for upload PDF files in Woocommerce product in admin

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;

Function to generate multiple metaboxes in WordPress

I've successfully been able to create one custom metabox for WordPress post types using the following code:
function bandcamp_metabox(){
$posttypes = Array(
'discos',
'Projetos'
);
add_meta_box('bandcamp_link', 'bandcamp link', 'bandcamp_link_meta_callback', $posttypes, 'side');
}
function bandcamp_link_meta_callback( $post ) {
wp_nonce_field('save_bandcamp_link', 'bancamp_meta_box_nonce');
$value = get_post_meta($post->ID,'_bandcamp_link_value_key', true);
echo '<label for="bancamp_link_field">';
echo '<input type="url" id="bancamp_link_field" name="bancamp_link_field" value="' . esc_attr ( $value ) . '" size="25" />';
}
function save_bandcamp_link ( $post_id ) {
if( ! isset( $_POST['bancamp_meta_box_nonce'] ) ){
return;
}
if ( ! wp_verify_nonce( $_POST['bancamp_meta_box_nonce'], 'save_bandcamp_link' ) ){
return;
}
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE){
return;
}
if( ! current_user_can( 'edit_post', $post_id ) ){
return;
}
if( ! isset( $_POST['bancamp_link_field'] ) ) {
return;
}
$bandcamp_link = sanitize_text_field( $_POST['bancamp_link_field'] );
update_post_meta($post_id, '_bandcamp_link_value_key', $bandcamp_link);
}
add_action('add_meta_boxes', 'bandcamp_metabox');
add_action('save_post', 'save_bandcamp_link');
I was hoping (still kind of a noob) that through a 'foreach' function I'd be able to re-use the code to create multiple metaboxes at once like this:
$varsocial = Array(
'bandcamp',
'soundcloud',
'facebook',
'instagram',);
foreach($varsocial as $sociallink) {
function social_metabox(){
$posttypes = Array(
'discos',
'Projetos');
add_meta_box(''. $sociallink .'_link', ''. $sociallink .' link', 'social_link_meta_callback', $posttypes, 'side');
}
function social_link_meta_callback( $post ) {
wp_nonce_field('save_social_link', 'social_meta_box_nonce');
$value = get_post_meta($post->ID,'_'. $sociallink .'_link_value_key', true);
echo '<label for="'. $sociallink .'_link_field">';
echo '<input type="url" id="'. $sociallink .'_link_field" name="'. $sociallink .'_link_field" value="' . esc_attr ( $value ) . '" size="25" />';
}
function save_social_link ( $post_id ) {
if( ! isset( $_POST['social_meta_box_nonce'] ) ){
return;
}
if ( ! wp_verify_nonce( $_POST['social_meta_box_nonce'], 'save_social_link' ) ){
return;
}
if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE){
return;
}
if( ! current_user_can( 'edit_post', $post_id ) ){
return;
}
if( ! isset( $_POST[''. $sociallink .'_link_field'] ) ) {
return;
}
$social_link = sanitize_text_field( $_POST[''. $sociallink .'_link_field'] );
update_post_meta($post_id, '_'. $sociallink .'_link_value_key', $social_link);}
return add_action('add_meta_boxes', 'social_metabox');
return add_action('save_post', 'save_social_link');
}
But such is not working. What am I doing wrong?

Show multiple product custom fields values in cart on Woocommerce

I have a problem with custom fields & values from my product page appearing on the cart page. As you can see from the screenshots, I have three fields: "Color," "Texto1" and "Texto2" and only the first seems to appear on my cart page.
This is the code that print the fields on the product page:
// Field 1
if( ! empty( $FieldType1 ) ){
if( $FieldType1 == "TEXT AREA"){
echo '<div>
<label>'.$FieldName1.':<br></label> <textarea name="FieldTypeValue1" maxlength="'.$FieldLenght1.'" rows="2" cols="80" placeholder="" required></textarea>
</div><br>';
}
if( $FieldType1 == "TEXT BOX"){
echo '<div>
<label>'.$FieldName1.':<br></label> <input type="text" maxlength="'.$FieldLenght1.'" name="FieldTypeValue1" value="" required>
</div><br>';
}
if( $FieldType1 == "DROP DOWN"){
echo '<div>
<label>'.$FieldName1.':<br></label>
<select name="FieldTypeValue1">';
foreach ($Dropdown1Content as $Dropdown1IndividualContent) {
echo '<option>';
echo $Dropdown1IndividualContent;
echo '</option>';
}
echo '</select></div><br>';
}
}
// Field 2
if( ! empty( $FieldType2 ) ){
if( $FieldType2 == "TEXT AREA"){
echo '<div>
<label>'.$FieldName2.':<br></label> <textarea name="FieldTypeValue2" maxlength="'.$FieldLenght2.'" rows="2" cols="80" placeholder="" required></textarea>
</div><br>';
}
if( $FieldType2 == "TEXT BOX"){
echo '<div>
<label>'.$FieldName2.':<br></label> <input type="text" maxlength="'.$FieldLenght2.'" name="FieldTypeValue2" value="" required>
</div><br>';
}
if( $FieldType2 == "DROP DOWN"){
echo '<div>
<label>'.$FieldName2.':<br></label>
<select name="FieldTypeValue2">';
foreach ($Dropdown2Content as $Dropdown2IndividualContent) {
echo '<option>';
echo $Dropdown2IndividualContent;
echo '</option>';
}
echo '</select></div><br>';
}
}
// Field 3
if( ! empty( $FieldType3 ) ){
if( $FieldType3 == "TEXT AREA"){
echo '<div>
<label>'.$FieldName3.':<br></label> <textarea name="FieldTypeValue3" maxlength="'.$FieldLenght3.'" rows="2" cols="80" placeholder="" required></textarea>
</div><br>';
}
if( $FieldType3 == "TEXT BOX"){
echo '<div>
<label>'.$FieldName3.':<br></label> <input type="text" maxlength="'.$FieldLenght3.'" name="FieldTypeValue3" value="" required>
</div><br>';
}
if( $FieldType3 == "DROP DOWN"){
echo '<div>
<label>'.$FieldName3.':<br></label>
<select name="FieldTypeValue3">';
foreach ($Dropdown3Content as $Dropdown3IndividualContent) {
echo '<option>';
echo $Dropdown3IndividualContent;
echo '</option>';
}
echo '</select></div><br>';
}
}
This is the code that saves the value of the fields on the product page
// Store custom field label and value in cart item data
add_action( 'woocommerce_add_cart_item_data','save_my_custom_checkout_field', 10, 2 );
function save_my_custom_checkout_field( $cart_item_data, $product_id ) {
if( isset( $_REQUEST['FieldTypeValue1'] ) ) {
$cart_item_data['custom_data']['label'] = get_post_meta($product_id, 'FieldName1', true);
$cart_item_data['custom_data']['value'] = sanitize_text_field( $_REQUEST['FieldTypeValue1'] );
$cart_item_data['custom_data']['ukey'] = md5( microtime().rand() );
}
return $cart_item_data;
if( isset( $_REQUEST['FieldTypeValue2'] ) ) {
$cart_item_data['custom_data']['label'] = get_post_meta($product_id, 'FieldName2', true);
$cart_item_data['custom_data']['value'] = sanitize_text_field( $_REQUEST['FieldTypeValue2'] );
$cart_item_data['custom_data']['ukey'] = md5( microtime().rand() );
}
return $cart_item_data;
if( isset( $_REQUEST['FieldTypeValue3'] ) ) {
$cart_item_data['custom_data']['label'] = get_post_meta($product_id,'FieldName3', true);
$cart_item_data['custom_data']['value'] = sanitize_text_field( $_REQUEST['FieldTypeValue3'] );
$cart_item_data['custom_data']['ukey'] = md5( microtime().rand() );
}
return $cart_item_data;
And this is the one that print the values on the cart:
// Display items custom fields label and value in cart and checkout pages
add_filter( 'woocommerce_get_item_data', 'render_meta_on_cart_and_checkout', 10, 2 );
function render_meta_on_cart_and_checkout( $cart_data, $cart_item ){
$custom_items = array();
/* Woo 2.4.2 updates */
if( !empty( $cart_data ) ) {
$custom_items = $cart_data;
}
if( isset( $cart_item['custom_data'] ) ) {
$custom_items[] = array(
'name' => $cart_item['custom_data']['label'],
'value' => $cart_item['custom_data']['value'],
);
}
return $custom_items;
}
The Custom fields on product page:
The product in cart (with the missing data):
I'm not sure if the problem is at the point where values are saved or at the point where they are printed.
Any help would be much appreciated.
Try this hooked functions instead, where I have revisited your code to make it work:
// Store custom field label and value in cart item data
add_filter( 'woocommerce_add_cart_item_data','save_my_custom_checkout_field', 20, 2 );
function save_my_custom_checkout_field( $cart_item_data, $product_id ) {
$label1 = get_post_meta( $product_id, 'FieldName1', true );
$label2 = get_post_meta( $product_id, 'FieldName2', true );
$label3 = get_post_meta( $product_id, 'FieldName3', true );
if( isset( $_REQUEST['FieldTypeValue1'] ) && ! empty( $label1 ) )
$cart_item_data['custom_data']['1'] = array(
'label' => $label1,
'value' => sanitize_text_field( $_REQUEST['FieldTypeValue1'] ),
);
if( isset( $_REQUEST['FieldTypeValue2'] ) && ! empty( $label2 ) )
$cart_item_data['custom_data']['2'] = array(
'label' => $label2,
'value' => sanitize_text_field( $_REQUEST['FieldTypeValue2'] ),
);
if( isset( $_REQUEST['FieldTypeValue3'] ) && ! empty( $label3 ) )
$cart_item_data['custom_data']['3'] = array(
'label' => $label3,
'value' => sanitize_text_field( $_REQUEST['FieldTypeValue3'] ),
);
if( count($cart_item_data['custom_data']) > 0 )
$cart_item_data['custom_data']['key'] = md5( microtime().rand() );
return $cart_item_data;
}
// Display items custom fields label and value in cart and checkout pages
add_filter( 'woocommerce_get_item_data', 'render_meta_on_cart_and_checkout', 20, 2 );
function render_meta_on_cart_and_checkout( $cart_data, $cart_item ){
$custom_items = array();
if( !empty( $cart_data ) )
$custom_items = $cart_data;
if( isset( $cart_item['custom_data'] ) ) {
foreach( $cart_item['custom_data'] as $key => $custom_data ){
if( $key != 'key' ){
$custom_items[] = array(
'name' => $custom_data['label'],
'value' => $custom_data['value'],
);
}
}
}
return $custom_items;
}
Code goes in function.php file of your active child theme (or active theme).
Tested and works… You will get something like that:
For testing I have used the following to display the 3 custom fields on single product page:
// Displaying 3 custom fields on single product pages
add_action( 'woocommerce_before_add_to_cart_button', 'add_custom_fields_single_product', 20 );
function add_custom_fields_single_product(){
global $product;
echo '<div>
<label>'.__('Color').': </label><br>
<input type="text" name="FieldTypeValue1" value="" required>
</div><br>';
echo '<div>
<label>'.__('Texto 1').': </label><br>
<input type="text" name="FieldTypeValue2" value="" required>
</div><br>';
echo '<div>
<label>'.__('Texto 2').': </label><br>
<input type="text" name="FieldTypeValue3" value="" required>
</div><br>';
}
Changing the following for testing purpose only (in the functions code):
$label1 = get_post_meta( $product_id, 'FieldName1', true );
$label2 = get_post_meta( $product_id, 'FieldName2', true );
$label3 = get_post_meta( $product_id, 'FieldName3', true );
by:
$label1 = __('Color');
$label2 = __('Texto 1');
$label3 = __('Texto 2');

How To Show Chechbox Result From Metabox To Single Post Wordpress?

Ask to everyone, i have problem. Here i try to use multiple chechbox to my custom post metabox.
<?php
function prodetail() {
add_meta_box('pro_metabox', 'Detail Property', 'pro_metabox', 'property', 'normal', 'default');
}
function pro_metabox() {
global $post;
echo '<input type="hidden" name="eventmeta_noncename" id="eventmeta_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
$postmeta = maybe_unserialize( get_post_meta( $post->ID, 'elements', true ) );
$elements = array(
'pool' => 'Pool',
'garage' => 'Garage',
'balcon' => 'Balcon',
'yard' => 'Yard',
'internet' => 'Internet'
);
foreach ( $elements as $id => $element) {
if ( is_array( $postmeta ) && in_array( $id, $postmeta ) ) {
$checked = 'checked="checked"';
} else {
$checked = null;
}
?>
<div class="pro-inn">
<div class="procols">
<div class="pro-inn">
<input type="checkbox" name="multval[]" value="<?php echo $id; ?>" <?php echo $checked; ?> />
<?php echo $element;?>
</div>
</div>
</div>
<?php
}
}
function pro_meta($post_id, $post) {
if ( !wp_verify_nonce( $_POST['eventmeta_noncename'], plugin_basename(__FILE__) )) {
return $post->ID;
}
if ( !current_user_can( 'edit_post', $post->ID ))
return $post->ID;
if ( ! empty( $_POST['multval'] ) ) {
update_post_meta( $post_id, 'elements', $_POST['multval'] );
} else {
delete_post_meta( $post_id, 'elements' );
}
}
add_action('save_post', 'pro_meta', 1, 2);
?>
help me to add code to show this checked result to single.php because my code use foreach just show Array text not show text like Pool Garage Balcon ect.
Thanks
Use this code in your single.php file for your custom post
$meta_value = get_post_meta( $post->ID, 'elements', true );
foreach($meta_value as $key=>$value){
echo $value . ' ';
}
It will show results same as you mentioned in the question ie:
(Pool Garage Balcon ect.)

How to count total number of Rating from the Extend Comment Plugin?

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;
}

Categories