My metabox data are not saving - wordpress

I am facing a problem which start to drive me nuts.I have created a metabox for my wordpress site. For the testings, I used it on a page. Everything went fine, without problems, but when I try to use the very same metabox in the media file (attachment) I am not able to save the datas. The metabox is properly displayed there, but I am unable to save any datas I enter in.
I must be missing something but can't figure out what.
Thanks in advance for your help
Kind regards
Alain
Here is the code:
<?php
$meta_box = array(
'id' => 'onzeroadagain-meta-box',
'title' => 'Prints size and price availablility',
'page' => 'attachment',
'context' => 'normal',
'priority' => 'high',
'fields' => array(
array(
'name' => 'Small',
'id' => 'small-checkbox',
'type' => 'checkbox'
),
array(
'name' => 'Dimensions',
'id' => 'dimension-small',
'type' => 'text',
'std' => 'W x H in cm'
),
array(
'name' => 'Price',
'id' => 'price-small',
'type' => 'text',
'std' => 'in Euro'
),
array(
'name' => 'Medium',
'id' => 'medium-checkbox',
'type' => 'checkbox'
),
array(
'name' => 'Dimensions',
'id' => 'dimension-medium',
'type' => 'text',
'std' => 'W x H in cm'
),
array(
'name' => 'Price',
'id' => 'price-medium',
'type' => 'text',
'std' => 'in Euro'
),
array(
'name' => 'Large',
'id' => 'large-checkbox',
'type' => 'checkbox'
),
array(
'name' => 'Dimensions',
'id' => 'dimension-large',
'type' => 'text',
'std' => 'W x H in cm'
),
array(
'name' => 'Price',
'id' => 'price-large',
'type' => 'text',
'std' => 'in Euro'
)
)
);
add_action('admin_menu', 'onzeroadagain_add_box');
// Add meta box
function onzeroadagain_add_box() {
global $meta_box;
add_meta_box($meta_box['id'], $meta_box['title'], 'onzeroadagain_show_box', $meta_box['page'], $meta_box['context'], $meta_box['priority']);
}
// Callback function to show fields in meta box
function onzeroadagain_show_box() {
global $meta_box, $post;
// Use nonce for verification
echo '<input type="hidden" name="onzeroadagain_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';
echo '<table class="form-table">';
foreach ($meta_box['fields'] as $field) {
// get current post meta data
$meta = get_post_meta($post->ID, $field['id'], true);
echo '<tr>',
'<th style="width:20%"><label for="', $field['id'], '">', $field['name'], '</label></th>',
'<td>';
switch ($field['type']) {
case 'checkbox':
echo '<input type="checkbox" name="', $field['id'], '" id="', $field['id'], '"', $meta ? ' checked="checked"' : '', ' />';
break;
case 'text':
echo '<input type="text" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : $field['std'], '" size="30" style="width:30%" />', '<br />', $field['desc'];
break;
}
echo '</td><td>',
'</td></tr>';
}
echo '</table>';
}
add_action('save_post', 'onzeroadagain_save_data');
// Save data from meta box
function onzeroadagain_save_data($post_id) {
global $meta_box;
// verify nonce
if (!wp_verify_nonce($_POST['onzeroadagain_meta_box_nonce'], basename(__FILE__))) {
return $post_id;
}
// check autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return $post_id;
}
// check permissions
if ('page' == $_POST['post_type']) {
if (!current_user_can('edit_page', $post_id)) {
return $post_id;
}
} elseif (!current_user_can('edit_post', $post_id)) {
return $post_id;
}
foreach ($meta_box['fields'] as $field) {
$old = get_post_meta($post_id, $field['id'], true);
$new = $_POST[$field['id']];
if ($new && $new != $old) {
update_post_meta($post_id, $field['id'], $new);
} elseif ('' == $new && $old) {
delete_post_meta($post_id, $field['id'], $old);
}
}
}

I encountered the same problem lately. I had two different sets of metaboxes, one on the side and one on the 'normal' column. The fields in my 'side' metaboxes were saving fine but not the ones in 'normal'. I tried changing the context of my second one to 'side' instead of 'normal' and BAM! Everything saved fine.
So I suggest you try that too and tell us if it works.
I did some research but I found no explanation to this. There might be something I don't undestand and do the wrong way, or could be some kind of bug. I'll keep investigating.

Hi modify your code like below:
add_action('save_post', 'onzeroadagain_save_data');
add_action( 'edit_attachment', 'onzeroadagain_save_data' );
The Key is:
'edit_attachment'

Related

Wordpress CPT add new overwrites existing ones

I'm working on a Wordpress projekt and added some custom post types and metaboxes. Inside my VM it all works fine, but on the server, the second CPT I add overwrites the previous one. This only happens for the CPT shops, the other ones I've added work like they should.
I've placed the code for CPT and the metaboxes in different files and included them inside my functions.php for each CPT.
Here's the file custom-post-type-shop.php for the shop
<?php
/**
* Plugin Name: BUYeinander Shops
* Version: 0.1
* Text Domain: buy_shops
**/
// Register Shop Custom Post Type
function buy_shops()
{
$labels = array(
'name' => _x('Shops', 'Post Type General Name', 'buy_shops'),
'singular_name' => _x('Shop', 'Post Type Singular Name', 'buy_shops'),
'menu_name' => __('Shops', 'buy_shops'),
'name_admin_bar' => __('Shops', 'buy_shops'),
'archives' => __('Shop Archives', 'buy_shops'),
'attributes' => __('Shop Attributes', 'buy_shops'),
'parent_item_colon' => __('Parent Shop:', 'buy_shops'),
'all_items' => __('All Shops', 'buy_shops'),
'add_new_item' => __('Add New Shop', 'buy_shops'),
'add_new' => __('Add New', 'buy_shops'),
'new_item' => __('New Shop', 'buy_shops'),
'edit_item' => __('Edit Shop', 'buy_shops'),
'update_item' => __('Update Shop', 'buy_shops'),
'view_item' => __('View Shop', 'buy_shops'),
'view_items' => __('View Shops', 'buy_shops'),
'search_items' => __('Search Shop', 'buy_shops'),
'not_found' => __('Not found', 'buy_shops'),
'not_found_in_trash' => __('Not found in Trash', 'buy_shops'),
'featured_image' => __('Shop Image', 'buy_shops'),
'set_featured_image' => __('Set Shop image', 'buy_shops'),
'remove_featured_image' => __('Remove Shop image', 'buy_shops'),
'use_featured_image' => __('Use as Shop image', 'buy_shops'),
'insert_into_item' => __('Insert into Shop', 'buy_shops'),
'uploaded_to_this_item' => __('Uploaded to this Shop', 'buy_shops'),
'items_list' => __('Shops list', 'buy_shops'),
'items_list_navigation' => __('Shops list navigation', 'buy_shops'),
'filter_items_list' => __('Filter Shops list', 'buy_shops'),
);
$args = array(
'label' => __('Shops', 'buy_shops'),
'description' => __('Shop-Eintrag', 'buy_shops'),
'labels' => $labels,
'supports' => array(
'title',
// 'editor',
// 'thumbnail',
// 'comments',
'revisions',
// 'custom-fields'
),
// 'taxonomies' => array( 'category' ),
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 20,
'menu_icon' => 'dashicons-store',
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'capability_type' => 'page',
'show_in_rest' => true,
);
register_post_type('Shops', $args);
}
add_action('init', 'buy_shops', 0);
This is the file meta-box-shop.php for the metabox
<?php
// Metabox for shops
$prefix_shop = 'buy_shop_';
$regionargs = array(
'post_type' => "regionen",
'post_status' => 'publish'
);
$regionquery = new WP_Query($regionargs);
$regions = [];
if ($regionquery->have_posts()) {
while ($regionquery->have_posts()) {
$regionquery->the_post();
$regionTitle = $regionquery->post->post_title;
if (!in_array($regionTitle, $regions)) {
$regions[] = $regionTitle;
}
}
}
$shop_meta_box = array(
'id' => 'shop-meta-box',
'title' => 'Shop Informationen',
'page' => 'Shops',
'context' => 'normal',
'priority' => 'high',
'fields' => array(
array(
'name' => 'Untertitel',
'desc' => '',
'id' => $prefix_shop . 'description',
'type' => 'text',
'std' => ''
),
array(
'name' => 'Straße',
'desc' => '',
'id' => $prefix_shop . 'street',
'type' => 'text',
'std' => ''
),
array(
'name' => 'Hausnummer',
'desc' => '',
'id' => $prefix_shop . 'housenumber',
'type' => 'number',
'std' => ''
),
array(
'name' => 'Postleitzahl',
'desc' => '',
'id' => $prefix_shop . 'zipcode',
'type' => 'number',
'std' => ''
),
array(
'name' => 'Stadt',
'desc' => '',
'id' => $prefix_shop . 'city',
'type' => 'text',
'std' => ''
),
array(
'name' => 'Internetadresse',
'desc' => '',
'id' => $prefix_shop . 'url',
'type' => 'text',
'std' => ''
),
array(
'name' => 'Region',
'desc' => '',
'id' => $prefix_shop . 'region',
'type' => 'select',
'std' => '',
'options' => $regions
),
array(
'name' => 'Zweigstelle',
'desc' => '',
'id' => $prefix_shop . 'branch',
'type' => 'checkbox',
'std' => ''
),
)
);
add_action('admin_menu', 'shop_add_box');
// Add meta box
function shop_add_box()
{
global $shop_meta_box;
add_meta_box($shop_meta_box['id'], $shop_meta_box['title'], 'shop_show_box', $shop_meta_box['page'], $shop_meta_box['context'], $shop_meta_box['priority']);
}
// Callback function to show fields in meta box
function shop_show_box()
{
global $shop_meta_box, $post;
// Use nonce for verification
echo '<input type="hidden" name="shop_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';
echo '<table class="form-table">';
foreach ($shop_meta_box['fields'] as $field) {
// get current post meta data
$meta = get_post_meta($post->ID, $field['id'], true);
echo '<tr>',
'<th style="width:20%"><label for="', $field['id'], '">', $field['name'], '</label></th>',
'<td>';
switch ($field['type']) {
case 'text':
echo '<input type="text" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : $field['std'], '" size="30" style="width:97%" />', '<br />', $field['desc'];
break;
case 'number':
echo '<input type="number" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : $field['std'], '" size="30" style="width:50%" />', '<br />', $field['desc'];
break;
// case 'textarea':
// echo '<textarea name="', $field['id'], '" id="', $field['id'], '" cols="60" rows="4" style="width:97%">', $meta ? $meta : $field['std'], '</textarea>', '<br />', $field['desc'];
// break;
case 'select':
echo '<select name="', $field['id'], '" id="', $field['id'], '">';
foreach ($field['options'] as $option) {
echo '<option ', $meta == $option ? ' selected="selected"' : '', '>', $option, '</option>';
}
echo '</select>';
break;
// case 'radio':
// foreach ($field['options'] as $option) {
// echo '<input type="radio" name="', $field['id'], '" value="', $option['value'], '"', $meta == $option['value'] ? ' checked="checked"' : '', ' />', $option['name'];
// }
break;
case 'checkbox':
echo '<input type="checkbox" name="', $field['id'], '" id="', $field['id'], '"', $meta ? ' checked="checked"' : '', ' />';
break;
}
echo '</td><td>',
'</td></tr>';
}
echo '</table>';
}
add_action('save_post', 'shop_save_data');
// Save data from meta box
function shop_save_data($post_id)
{
global $shop_meta_box;
// verify nonce
if (!wp_verify_nonce($_POST['shop_meta_box_nonce'], basename(__FILE__))) {
return $post_id;
}
// check autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return $post_id;
}
// check permissions
if ('page' == $_POST['post_type']) {
if (!current_user_can('edit_page', $post_id)) {
return $post_id;
}
} elseif (!current_user_can('edit_post', $post_id)) {
return $post_id;
}
foreach ($shop_meta_box['fields'] as $field) {
$old = get_post_meta($post_id, $field['id'], true);
$new = $_POST[$field['id']];
if ($new && $new != $old) {
update_post_meta($post_id, $field['id'], $new);
} elseif ('' == $new && $old) {
delete_post_meta($post_id, $field['id'], $old);
}
}
}
/*
* Add a meta box for image upload
*/
function lacuna2_case_study_bg( $post ) {
wp_nonce_field( 'case_study_bg_submit', 'case_study_bg_nonce' );
$lacuna2_stored_meta = get_post_meta( $post->ID ); ?>
<p>
<img style="max-width:200px;height:auto;" id="meta-image-preview" src="<?php if ( isset ( $lacuna2_stored_meta['meta-image'] ) ){ echo $lacuna2_stored_meta['meta-image'][0]; } ?>" /> <br>
<input type="text" name="meta-image" id="meta-image" class="meta_image" value="<?php if ( isset ( $lacuna2_stored_meta['meta-image'] ) ){ echo $lacuna2_stored_meta['meta-image'][0]; } ?>" />
<input type="button" id="meta-image-button" class="button" value="Choose or Upload an Image" />
</p>
<script>
jQuery('#meta-image-button').click(function() {
var send_attachment_bkp = wp.media.editor.send.attachment;
wp.media.editor.send.attachment = function(props, attachment) {
jQuery('#meta-image').val(attachment.url);
jQuery('#meta-image-preview').attr('src',attachment.url);
wp.media.editor.send.attachment = send_attachment_bkp;
}
wp.media.editor.open();
return false;
});
</script>
<?php
}
/**
* Add Case Study background image metabox to the back end of Case Study posts
*/
function lacuna2_add_meta_boxes() {
add_meta_box( 'case-study-bg', 'Shop Bilddatei', 'lacuna2_case_study_bg', 'shops', 'normal', 'high' );
}
add_action( 'add_meta_boxes', 'lacuna2_add_meta_boxes' );
/**
* Save background image metabox for Case Study posts
*/
function save_case_study_bg_meta_box( $post_id ) {
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'case_study_bg_nonce' ] ) && wp_verify_nonce( $_POST[ 'case_study_bg_nonce' ], 'case_study_bg_submit' ) ) ? 'true' : 'false';
// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
// Checks for input and sanitizes/saves if needed
if( isset( $_POST[ 'meta-image' ] ) ) {
update_post_meta( $post_id, 'meta-image', $_POST[ 'meta-image' ] );
}
}
add_action( 'save_post', 'save_case_study_bg_meta_box' );
1) Make sure both post_types use an unique post_type key. That is the first parameter for the register_post_type function. See docs: https://developer.wordpress.org/
2) Also: make sure to use a post_type key with only lowercase characters. As I may quote the documentation:
$post_type (string) (Required) Post type key. Must not exceed 20
characters and may only contain lowercase alphanumeric characters,
dashes, and underscores.
So change:
register_post_type('Shops', $args);
into:
register_post_type('shops', $args);
In register_post_type() function, you have to put a unique post_type_key for each Custom Post Type. You're providing the same post_type_key for both Custom Post Type that's why the second one is overriding the first one. As you're using
register_post_type('shops', $args);
for the first one, you should use something else as post_type_key at the first parameter for the second Custom Post Type. You have to use anything unique for this. For example,
register_post_type('my-shop', $args);
Visit the official doc for details.

WooCommerce add heading at start of custom fields

I have created custom fields in my WooCommerce checkout page billing form. It all works fine but I am trying to add an h3 element with text in between. So basically I ask for some additional information in the billing form, but I want to give that a heading.
I tried to create a h3 dynamically with Javascript/jQuery and insert before the specific id I want it to be. But this didn't work as I liked and I rather have a server-side solution.
Thanks in advance!
Here's the function where I define my custom fields. I've tried an echo at the beginning but it ends up displaying at the top of the entire form.
// Modify billing fields
add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
function custom_override_checkout_fields( $fields ) {
unset($fields['billing']['billing_phone']);
unset($fields['billing']['billing_email']);
//echo '<h3>Wie is de verzender?</h3>';
$fields['billing']['name_sender'] = array(
'label' => __('Uw naam', 'woocommerce'),
'required' => true,
'class' => array('form-row-wide'),
'clear' => true
);
$fields['billing']['email_sender'] = array(
'label' => __('Uw email', 'woocommerce'),
'required' => true,
'class' => array('form-row-wide'),
'clear' => true
);
$fields['billing']['phone_sender'] = array(
'label' => __('Uw telefoonnummer', 'woocommerce'),
'required' => true,
'class' => array('form-row-wide'),
'clear' => true
);
$fields['billing']['anoniem'] = array(
'label' => __('Anoniem verzenden?', 'woocommerce'),
'type' => 'checkbox',
'class' => array('form-row-wide'),
'clear' => true
);
return $fields;
}
A visual explanation:
Visual explanation
You can hook into the woocommerce_form_field_<field_type> filter. This allows us to add HTML output for an additional field type (and in this case we can output HTML for a heading instead) and we can use this new heading "field type" when modifying checkout fields with the woocommerce_checkout_fields filter.
// Add field type to WooCommerce form field
add_filter( 'woocommerce_form_field_heading','sc_woocommerce_form_field_heading', 10, 4 );
function sc_woocommerce_form_field_heading($field, $key, $args, $value) {
$output = '<h3 class="form-row form-row-wide">'.__( $args['label'], 'woocommerce' ).'</h3>';
echo $output;
}
// Modify checkout fields
add_filter( 'woocommerce_checkout_fields','custom_override_checkout_fields' );
function custom_override_checkout_fields( $fields ) {
$fields['billing']['billing_heading_name'] = array(
'type' => 'heading',
'label' => 'Heading here',
);
When modifying fields using the woocommerce_checkout_fields filter you can now place your new heading field in any position you need.
function filter_woocommerce_form_field_radio( $field, $key, $args, $value ) {
// Based on key
if ( $key == 'radio_choice' ) {
if ( ! empty( $args['options'] ) ) {
$field = '<div><h1>Heading</h1><ul>';
foreach ( $args['options'] as $option_key => $option_text ) {
$field .= '<li>';
$field .= '<input type="radio" value="' . esc_attr( $option_key ) . '" name="' . esc_attr( $key ) . '" id="' . esc_attr( $args['id'] ) . '_' . esc_attr( $option_key ) . '" />';
$field .= '<label>' . esc_html( $option_text ) . '</label>';
$field .= '</li>';
}
$field .= '</ul></div>';
}
}
return $field;
}
add_filter( 'woocommerce_form_field_radio', 'filter_woocommerce_form_field_radio', 10, 4 );

How to use the visual composer attach_images as in a shortcode

I am trying to create a custom image slider using visual composers attach_images but cant quite work out how to get the URLs from the array of image IDs.
Any help would be appreciated.
var_dump($bg_images) returns
string(9) "19,6,1692"
vc_map( array(
"name" => __( "Fading Background Block", "farrat_vc" ),
"base" => "block_background",
"class" => "",
"category" => __( "Farrat Shortcodes", "farrat_vc"),
"as_parent" => array('except' => 'farrat_panel'), // Use only|except attributes to limit child shortcodes (separate multiple values with comma)
"content_element" => true,
"show_settings_on_create" => true,
"is_container" => true,
'admin_enqueue_css' => array(get_template_directory_uri().'/wp-content/themes/unite/inc/css/gallery.css'),
"params" => array(
array(
"type" => "attach_images",
"heading" => __( "Backgroud Images", "farrat_vc" ),
"param_name" => "bg_images",
),
),
"js_view" => 'VcColumnView'
) );
// Hi try this one this is perfectly working
//Param Registration
function designas_partners() {
// Title
vc_map(
array(
'name' => __( 'Clients' ),
'base' => 'designas_partners_content',
'category' => __( 'Easy Component' ),
'params' => array(
array(
"type" => "attach_images",
"heading" => esc_html__( "Add Clients Images", "appcastle-core" ),
"description" => esc_html__( "Add Clients Images", "appcastle-core" ),
"param_name" => "screenshots",
"value" => "",
),
)
)
);
}
add_action( 'vc_before_init', 'designas_partners' );
// Short code
function designas_partners_content_function( $atts, $content ) {
$gallery = shortcode_atts(
array(
'screenshots' => 'screenshots',
), $atts );
$image_ids = explode(',',$gallery['screenshots']);
$return = '
<div class="clients">';
foreach( $image_ids as $image_id ){
$images = wp_get_attachment_image_src( $image_id, 'company_logo' );
$return .='<div class="images"><img src="'.$images[0].'" alt="'.$atts['title'].'"></div>';
$images++;
}
$return .='</div>';
return $return;
}
add_shortcode( 'designas_partners_content', 'designas_partners_content_function' )
I got a neet workaround for this one on the loop, theres no need for the counter, loop over wp_get_attachment_image( $image_id, 'full' ); will get you every information u use on the wordpress panel.
I'll thank to #sushovan bhowmik was looking for this, I think this will help to avoid lots of variables calling the images :)
<?php
function vc_gallery_carrousel($atts, $content) {
// Attributes
$gallery = shortcode_atts(
array(
'carrousel_images' => 'carrousel_images',
),
$atts );
// Attributes in var
$image_ids=explode(',',$gallery['carrousel_images']);
// Output Code
$output .= '<section class="loopclientsimg">';
$output .= '<article>';
$output .= '<div>';
$output .= '<ul>';
foreach( $image_ids as $image_id ){
$output .='<li>';
$output .= wp_get_attachment_image( $image_id, 'full' );
$output .='</li>';
}
$output .= '</ul>';
$output .= '</div>';
$output .= '</article>';
$output .= '</section>';
return $output;
}
add_shortcode( 'vc_img_carrousel', 'vc_gallery_carrousel' );

Wordpress - creating meta boxes and saving

I'm trying to create a metabox, it should be nice and easy but I'm getting it wrong. It pertains to a tour custom post, and adding the price in for that tour:
So initially I create this custom post type (this works):
register_post_type( 'tours',
array(
'labels' => array(
'name' => __( 'Tours' ),
'singular_name' => __( 'Tour' ),
'add_new' => 'Add New Tour Instance',
'add_new_item' => 'Add New Tour Instance',
'edit' => 'Edit',
'edit_item' => 'Edit Tour Instance',
'new_item' => 'New Tour Instance',
'view' => 'View',
'view_item' => 'View Tour Instance',
'search_items' => 'Search Tour Instances',
'not_found' => 'No Tour Instances found',
'not_found_in_trash' => 'No Tour Instances found in Rubbish',
'parent' => 'Parent Tour Instance'
),
'public' => true,
'supports' => array( 'title', 'editor', 'thumbnail'),
'taxonomies' => array( '' ),
//'menu_icon' => plugins_url( 'images/image.png', __FILE__ ),
'capability_type' => 'post',
'rewrite' => array("slug" => "tours") // Permalinks format
)
);
Then I create the box itself (this also works):
add_action( 'admin_init', 'tour_meta' );
function tour_meta() {
add_meta_box(
'tours_meta_box',
'Tour Price',
'display_tours_price_meta_box',
'tours',
'side',
'high'
);
}
Now, within the overall function, I then try to get the detail and save it:
function display_tours_price_meta_box() {
global $post;
// Noncename needed to verify where the data originated
echo '<input type="hidden" name="tourmeta_noncename" id="tourmeta_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
// Get the price data if its already been entered
$price = get_post_meta($post->ID, '_price', true);
echo 'Add the total cost for this tour here, do not include monetary characters like £ or $';
echo '<input type="text" name="_price" ' . $price . '" class="widefat" />';
}
function save_tours_meta($tour_id, $tour) {
if ( !wp_verify_nonce( $_POST['tourmeta_noncename'], plugin_basename(__FILE__) )) {
return $post->ID;
}
// Is the user allowed to edit the post or page?
if ( !current_user_can( 'edit_post', $post->ID ))
return $post->ID;
$tour_meta['_price'] = $_POST['_price'];
// Add values of $tour_meta as custom fields
foreach ($tour_meta as $key => $value) {
if( $post->post_type == 'revision' ) return;
$value = implode(',', (array)$value);
if(get_post_meta($post->ID, $key, FALSE)) {
update_post_meta($post->ID, $key, $value);
} else {
add_post_meta($post->ID, $key, $value);
}
if(!$value) delete_post_meta($post->ID, $key);
}
}
add_action('save_post', 'save_tours_meta', 1, 2);
The actual box appears, and the information is echo'd. However it does not save. I haven't the foggiest why. It must pertain to my last function, but I don't understand what is going wrong.
Thanks
You should better simplify your saving process like this :
function save_tours_meta($post_id) {
if ( !wp_verify_nonce( $_POST['tourmeta_noncename'], plugin_basename(__FILE__) )) {
// You don't need to return anything
return;
}
// Is the user allowed to edit the post or page?
if ( !current_user_can( 'edit_post', $post_id ) && !isset($_POST['_price']))
return;
// If you just have 1 value
update_post_meta($post_id, '_price', $_POST['_price']);
}
Just notice that the update_post_meta function will update the post meta or create it if it doesn't exist so don't bother usind add_post_meta.
I think it's your arguments. You declare the function as
function save_tours_meta($tour_id, $tour) {
but you're using (eg) $post->ID. $post in this case isn't the global variable, but the function argument. Try using $tour->ID or just $tour_id instead.
A couple of other (unrelated) things:
You can call update_post_meta() and it'll add the key if it doesn't exist, so you can remove your if statement (just reducing the lines of code).
Your "revision" check should return the post ID (and can be moved outside your loop)

Make table for this meta box? (wordpress)

I have been trying to display this meta box info in my template as a table, but it isn't working out.
What I want to do is make a simple table out of it. All I need is someone to help me start. The code for the meta box is done, but I have no idea how to output it.
$prefix = 'anime_';
$anime_box = array(
'id' => 'anime-meta-box',
'title' => 'Anime Details',
'page' => 'post',
'context' => 'normal',
'priority' => 'high',
'fields' => array(
array(
'name' => 'Name',
'desc' => 'Add the name of the Anime in either English or Japanese(Romanji).',
'id' => $prefix . 'anname',
'type' => 'text',
'std' => ''
),
array(
'name' => 'Genre',
'desc' => 'Is it a thriller, action/adventure, etc...',
'id' => $prefix . 'angenre',
'type' => 'text',
'std' => ''
),
array(
'name' => 'Directed by',
'desc' => 'Name of director(s).',
'id' => $prefix . 'an_director',
'type' => 'text',
'std' => ''
),
array(
'name' => 'Music by',
'desc' => 'Name of composer(s)',
'id' => $prefix . 'anmusic',
'type' => 'text',
'std' => ''
),
array(
'name' => 'Studio',
'desc' => 'Studio which owns the anime.',
'id' => $prefix . 'anstudio',
'type' => 'text',
'std' => ''
),
array(
'name' => 'Licensed by',
'desc' => 'Name of both American and Japanese license holders.',
'id' => $prefix . 'anlicense',
'type' => 'text',
'std' => ''
),
array(
'name' => 'Network(s)',
'desc' => 'Networks which air the show in both Japan and the United States.',
'id' => $prefix . 'annetwork',
'type' => 'text',
'std' => ''
),
array(
'name' => 'Original run',
'desc' => 'Date of when the anime first aired and when it stopped.',
'id' => $prefix . 'anrun',
'type' => 'text',
'std' => ''
),
array(
'name' => 'Episodes',
'desc' => 'Number of episodes.',
'id' => $prefix . 'anepisodes',
'type' => 'text',
'std' => ''
),
)
);
add_action('admin_menu', 'anime_add_box');
// Add meta box
function anime_add_box() {
global $anime_box;
add_meta_box($anime_box['id'], $anime_box['title'], 'anime_show_box', $anime_box['page'], $anime_box['context'], $anime_box['priority']);
}
// Callback function to show fields in meta box
function anime_show_box() {
global $anime_box, $post;
// Use nonce for verification
echo '<input type="hidden" name="anime_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';
echo '<table class="form-table">';
foreach ($anime_box['fields'] as $field) {
// get current post meta data
$meta = get_post_meta($post->ID, $field['id'], true);
echo '<tr>',
'<th style="width:20%"><label for="', $field['id'], '"><strong>', $field['name'], ':</strong></label></th>',
'<td>';
switch ($field['type']) {
case 'text':
echo '<input type="text" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : $field['std'], '" size="30" style="width:97%" />',
'<br /><small>', $field['desc'],'</small>';
break;
}
echo '<td>',
'</tr>';
}
echo '</table>';
}
add_action('save_post', 'anime_save_data');
// Save data from meta box
function anime_save_data($post_id) {
global $anime_box;
// verify nonce
if (!wp_verify_nonce($_POST['anime_meta_box_nonce'], basename(__FILE__))) {
return $post_id;
}
// check autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return $post_id;
}
// check permissions
if ('page' == $_POST['post_type']) {
if (!current_user_can('edit_page', $post_id)) {
return $post_id;
}
} elseif (!current_user_can('edit_post', $post_id)) {
return $post_id;
}
foreach ($anime_box['fields'] as $field) {
$old = get_post_meta($post_id, $field['id'], true);
$new = $_POST[$field['id']];
if ($new && $new != $old) {
update_post_meta($post_id, $field['id'], $new);
} elseif ('' == $new && $old) {
delete_post_meta($post_id, $field['id'], $old);
}
}
}
I tried using
<table>
<tr>
<td><?php echo get_post_meta($post->ID, "anname", true); ?></td>
</tr>
</table>
As a way to test it out one field, but it hasn't worked. Any ideas?
I believe the code you are using should be correct, however, the meta data ID you retrieving seems to be missing your prefix variable out: "anime_". Try:
<?php echo get_post_meta($post->ID, "anime_anname", true); ?>

Resources