Wordpress CPT add new overwrites existing ones - wordpress

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.

Related

My metabox data are not saving

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'

Custom post meta showing on localhost, but not live server?

I'm having an issue and, honestly, I have absolutely no idea what's going on...
I have some custom meta fields for my custom post type (called review). On my local installation, they appear and work perfectly:
However, on live, they don't show up! Completely vanished!
The panel is selected in Screen Options too, so that's not the issue:
Here is the code for my entire custom post type... perhaps I've done something stupid?
<?php
// Register Custom Post Type
function review() {
$labels = array(
'name' => 'Reviews',
'singular_name' => 'Review',
'menu_name' => 'Reviews',
'name_admin_bar' => 'Review',
'archives' => 'Review Archives',
'parent_item_colon' => 'Parent Item:',
'all_items' => 'All Items',
'add_new_item' => 'Add New Item',
'add_new' => 'Add New',
'new_item' => 'New Item',
'edit_item' => 'Edit Item',
'update_item' => 'Update Item',
'view_item' => 'View Item',
'search_items' => 'Search Item',
'not_found' => 'Not found',
'not_found_in_trash' => 'Not found in Trash',
'featured_image' => 'Featured Image',
'set_featured_image' => 'Set featured image',
'remove_featured_image' => 'Remove featured image',
'use_featured_image' => 'Use as featured image',
'insert_into_item' => 'Insert into item',
'uploaded_to_this_item' => 'Uploaded to this item',
'items_list' => 'Items list',
'items_list_navigation' => 'Items list navigation',
'filter_items_list' => 'Filter items list',
);
$args = array(
'label' => 'Review',
'description' => 'A product review',
'labels' => $labels,
'supports' => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions'),
'taxonomies' => array( 'category', 'post_tag' ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'menu_icon' => 'dashicons-edit',
'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',
);
register_post_type( 'review', $args );
}
add_action( 'init', 'review', 0 );
//Review options meta
/**
* Generated by the WordPress Meta Box generator
* at http://jeremyhixon.com/tool/wordpress-meta-box-generator/
*/
function review_options_get_meta( $value ) {
global $post;
$field = get_post_meta( $post->ID, $value, true );
if ( ! empty( $field ) ) {
return is_array( $field ) ? stripslashes_deep( $field ) : stripslashes( wp_kses_decode_entities( $field ) );
} else {
return false;
}
}
function review_options_add_meta_box() {
add_meta_box(
'review_options-review-options',
__( 'Review options', 'review_options' ),
'review_options_html',
'review',
'core',
'high'
);
}
add_action( 'add_meta_boxes', 'review_options_add_meta_box' );
function review_options_html( $post) {
wp_nonce_field( '_review_options_nonce', 'review_options_nonce' ); ?>
<p>Options for your reviews</p>
<p>
<label for="review_options_review_score"><?php _e( 'Review Score', 'review_options' ); ?></label><br>
<select name="review_options_review_score" id="review_options_review_score" style="width: 50%;">
<option <?php echo (review_options_get_meta( 'review_options_review_score' ) === '1' ) ? 'selected' : '' ?>>1</option>
<option <?php echo (review_options_get_meta( 'review_options_review_score' ) === '2' ) ? 'selected' : '' ?>>2</option>
<option <?php echo (review_options_get_meta( 'review_options_review_score' ) === '3' ) ? 'selected' : '' ?>>3</option>
<option <?php echo (review_options_get_meta( 'review_options_review_score' ) === '4' ) ? 'selected' : '' ?>>4</option>
<option <?php echo (review_options_get_meta( 'review_options_review_score' ) === '5' ) ? 'selected' : '' ?>>5</option>
<option <?php echo (review_options_get_meta( 'review_options_review_score' ) === '6' ) ? 'selected' : '' ?>>6</option>
<option <?php echo (review_options_get_meta( 'review_options_review_score' ) === '7' ) ? 'selected' : '' ?>>7</option>
<option <?php echo (review_options_get_meta( 'review_options_review_score' ) === '8' ) ? 'selected' : '' ?>>8</option>
<option <?php echo (review_options_get_meta( 'review_options_review_score' ) === '9' ) ? 'selected' : '' ?>>9</option>
<option <?php echo (review_options_get_meta( 'review_options_review_score' ) === '10' ) ? 'selected' : '' ?>>10</option>
</select>
</p> <p>
<label for="review_options_review_title_colour"><?php _e( 'Review title colour', 'review_options' ); ?></label><br>
<select name="review_options_review_title_colour" id="review_options_review_title_colour">
<option <?php echo (review_options_get_meta( 'review_options_review_title_colour' ) === '' ) ? 'selected' : '' ?>>Default</option>
<option <?php echo (review_options_get_meta( 'review_options_review_title_colour' ) === 'black' ) ? 'selected' : '' ?>>Black</option>
<option <?php echo (review_options_get_meta( 'review_options_review_title_colour' ) === 'white' ) ? 'selected' : '' ?>>White</option>
</select>
</p><?php
}
function review_options_save( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if ( ! isset( $_POST['review_options_nonce'] ) || ! wp_verify_nonce( $_POST['review_options_nonce'], '_review_options_nonce' ) ) return;
if ( ! current_user_can( 'edit_post', $post_id ) ) return;
if ( isset( $_POST['review_options_review_score'] ) )
update_post_meta( $post_id, 'review_options_review_score', esc_attr( $_POST['review_options_review_score'] ) );
if ( isset( $_POST['review_options_review_title_colour'] ) )
update_post_meta( $post_id, 'review_options_review_title_colour', esc_attr( $_POST['review_options_review_title_colour'] ) );
}
add_action( 'save_post', 'review_options_save' );
/*
Usage: review_options_get_meta( 'review_options_review_score' )
Usage: review_options_get_meta( 'review_options_review_title_colour' )
*/
?>
Or perhaps it's something to do with my only other post type?
<?php // Register Custom Post Type
function product() {
$labels = array(
'name' => _x( 'Products', 'Post Type General Name', 'text_domain' ),
'singular_name' => _x( 'Product', 'Post Type Singular Name', 'text_domain' ),
'menu_name' => __( 'Product', 'text_domain' ),
'name_admin_bar' => __( 'Product', 'text_domain' ),
'archives' => __( 'Products', 'text_domain' ),
'parent_item_colon' => __( 'Product', 'text_domain' ),
'all_items' => __( 'All Products', 'text_domain' ),
'add_new_item' => __( 'Add New Product', 'text_domain' ),
'add_new' => __( 'Add New', 'text_domain' ),
'new_item' => __( 'New Product', 'text_domain' ),
'edit_item' => __( 'Edit Product', 'text_domain' ),
'update_item' => __( 'Update Product', 'text_domain' ),
'view_item' => __( 'View Product', 'text_domain' ),
'search_items' => __( 'Search Products', 'text_domain' ),
'not_found' => __( 'Not found', 'text_domain' ),
'not_found_in_trash' => __( 'Not found in Trash', 'text_domain' ),
'featured_image' => __( 'Featured Image', 'text_domain' ),
'set_featured_image' => __( 'Set featured image', 'text_domain' ),
'remove_featured_image' => __( 'Remove featured image', 'text_domain' ),
'use_featured_image' => __( 'Use as featured image', 'text_domain' ),
'insert_into_item' => __( 'Insert into Product', 'text_domain' ),
'uploaded_to_this_item' => __( 'Uploaded to this Product', 'text_domain' ),
'items_list' => __( 'Product list', 'text_domain' ),
'items_list_navigation' => __( 'Product list navigation', 'text_domain' ),
'filter_items_list' => __( 'Filter Product list', 'text_domain' ),
);
$args = array(
'label' => __( 'Product', 'text_domain' ),
'description' => __( 'A product', 'text_domain' ),
'labels' => $labels,
'supports' => array( 'title', 'editor', 'thumbnail', ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 8,
'menu_icon' => 'dashicons-archive',
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => true,
'publicly_queryable' => true,
'capability_type' => 'page',
);
register_post_type( 'product', $args );
}
add_action( 'init', 'product', 0 );
//Creation of Meta Box for post type "destination_category" (Start)
add_action( 'admin_init', 'my_destination_category' );
//destination_sub_category_admin - is the required HTML id attribute
//Select Destination Sub Category - is the text visible in the heading of the meta box section
//display_destination_subcategory_meta_box - is the callback which renders the contents of the meta box
//destination_category - is the name of the custom post type where the meta box will be displayed
// normal - defines the part of the page where the edit screen section should be shown
// high - defines the priority within the context where the boxes should show
function my_destination_category() {
foreach( array( 'post', 'review' ) as $pt )
add_meta_box(
'destination_sub_category_admin',
'Select Destination Sub Category',
'display_destination_subcategory_meta_box',
$pt,
'normal',
'high');
function display_destination_subcategory_meta_box( $select_category ) {
// Retrieve Current Selected Category ID based on the Category Created
global $wpdb;
$selectcat="SELECT * FROM ".$wpdb->prefix."posts WHERE `post_type`='product' AND `post_status`='publish' ORDER BY `ID` DESC";
$resultant = $wpdb->get_results($selectcat);
$rescount=count($resultant);
$category_selected_id = intval( get_post_meta( $select_category->ID, 'destination_category_id', true ) );
?>
<table>
<tr>
<td style="width: 150px">Select Category</td>
<td>
<select style="width: 100px" name="category_selection" id="meta_box_category" style="float:left; width:50%; !important">
<?php
if($rescount==0)
{?>
<option value="null">No Posts have been created</option>
<?php
}
else
{
// Generate all items of drop-down list
?>
<option value="">None</option>
<?php
foreach($resultant as $singleresultant)
{
?>
<option value="<?php echo $singleresultant->ID; ?>" <?php echo selected( $singleresultant->ID, $category_selected_id ); ?>>
<?php echo $singleresultant->post_title; ?>
</option>
<?php
}
}
?>
</select>
</td>
</tr>
</table>
<?php
}
// Registering a Save Post Function
add_action( 'save_post', 'destination_admin_sub_category', 10, 2 );
function destination_admin_sub_category( $select_category_id, $select_category ) {
if ( $select_category->post_type == 'post' || 'review' ) {
if ( isset( $_POST['category_selection'] ) && $_POST['category_selection'] != '' ) {
echo update_post_meta( $select_category_id, 'destination_category_id', $_POST['category_selection'] );
} }
}
}
/**
* Generated by the WordPress Meta Box Generator at
*/
class Rational_Meta_Box {
private $screens = array(
'product',
);
private $fields = array(
array(
'id' => 'box-art',
'label' => 'Box Art',
'type' => 'media',
),
array(
'id' => 'developer',
'label' => 'Developer',
'type' => 'text',
),
array(
'id' => 'publisher',
'label' => 'Publisher',
'type' => 'text',
),
array(
'id' => 'release-date',
'label' => 'Release Date',
'type' => 'date',
),
);
/**
* Class construct method. Adds actions to their respective WordPress hooks.
*/
public function __construct() {
add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) );
add_action( 'admin_footer', array( $this, 'admin_footer' ) );
add_action( 'save_post', array( $this, 'save_post' ) );
}
/**
* Hooks into WordPress' add_meta_boxes function.
* Goes through screens (post types) and adds the meta box.
*/
public function add_meta_boxes() {
foreach ( $this->screens as $screen ) {
add_meta_box(
'product-options',
__( 'Product Options', 'product-options' ),
array( $this, 'add_meta_box_callback' ),
$screen,
'advanced',
'core'
);
}
}
/**
* Generates the HTML for the meta box
*
* #param object $post WordPress post object
*/
public function add_meta_box_callback( $post ) {
wp_nonce_field( 'product_options_data', 'product_options_nonce' );
echo 'Options for products';
$this->generate_fields( $post );
}
/**
* Hooks into WordPress' admin_footer function.
* Adds scripts for media uploader.
*/
public function admin_footer() {
?><script>
// https://codestag.com/how-to-use-wordpress-3-5-media-uploader-in-theme-options/
jQuery(document).ready(function($){
if ( typeof wp.media !== 'undefined' ) {
var _custom_media = true,
_orig_send_attachment = wp.media.editor.send.attachment;
$('.rational-metabox-media').click(function(e) {
var send_attachment_bkp = wp.media.editor.send.attachment;
var button = $(this);
var id = button.attr('id').replace('_button', '');
_custom_media = true;
wp.media.editor.send.attachment = function(props, attachment){
if ( _custom_media ) {
$("#"+id).val(attachment.url);
} else {
return _orig_send_attachment.apply( this, [props, attachment] );
};
}
wp.media.editor.open(button);
return false;
});
$('.add_media').on('click', function(){
_custom_media = false;
});
}
});
</script><?php
}
/**
* Generates the field's HTML for the meta box.
*/
public function generate_fields( $post ) {
$output = '';
foreach ( $this->fields as $field ) {
$label = '<label for="' . $field['id'] . '">' . $field['label'] . '</label>';
$db_value = get_post_meta( $post->ID, 'product_options_' . $field['id'], true );
switch ( $field['type'] ) {
case 'media':
$input = sprintf(
'<input class="regular-text" id="%s" name="%s" type="text" value="%s"> <input class="button rational-metabox-media" id="%s_button" name="%s_button" type="button" value="Upload" />',
$field['id'],
$field['id'],
$db_value,
$field['id'],
$field['id']
);
break;
default:
$input = sprintf(
'<input %s id="%s" name="%s" type="%s" value="%s">',
$field['type'] !== 'color' ? 'class="regular-text"' : '',
$field['id'],
$field['id'],
$field['type'],
$db_value
);
}
$output .= $this->row_format( $label, $input );
}
echo '<table class="form-table"><tbody>' . $output . '</tbody></table>';
}
/**
* Generates the HTML for table rows.
*/
public function row_format( $label, $input ) {
return sprintf(
'<tr><th scope="row">%s</th><td>%s</td></tr>',
$label,
$input
);
}
/**
* Hooks into WordPress' save_post function
*/
public function save_post( $post_id ) {
if ( ! isset( $_POST['product_options_nonce'] ) )
return $post_id;
$nonce = $_POST['product_options_nonce'];
if ( !wp_verify_nonce( $nonce, 'product_options_data' ) )
return $post_id;
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
foreach ( $this->fields as $field ) {
if ( isset( $_POST[ $field['id'] ] ) ) {
switch ( $field['type'] ) {
case 'email':
$_POST[ $field['id'] ] = sanitize_email( $_POST[ $field['id'] ] );
break;
case 'text':
$_POST[ $field['id'] ] = sanitize_text_field( $_POST[ $field['id'] ] );
break;
}
update_post_meta( $post_id, 'product_options_' . $field['id'], $_POST[ $field['id'] ] );
} else if ( $field['type'] === 'checkbox' ) {
update_post_meta( $post_id, 'product_options_' . $field['id'], '0' );
}
}
}
}
new Rational_Meta_Box;
?>
Either way, I have absolutely no idea why it's working perfectly locally and messing up on my live server... it's baffling!
Thanks in advance for your help!

WordPress Taxonomy Term meta not working with export and import

I have created a Taxonomy Meta Data for Custom Post Type and its working fine while saving, updating, editing etc. But its not working while importing or exporting with wordpress importer. Taxonomies meta data are not importing.
Here is the Code based on the Tutorial
<?php
if ( ! function_exists( 'register_cpt_houses' ) ) {
function register_cpt_houses() {
$labels = array(
'name' => __('houses', 'my_plugin'),
'singular_name' => __('houses', 'my_plugin'),
'add_new' => __('Add New','my_plugin'),
'add_new_item' => __('Add New Slide','my_plugin'),
'edit_item' => __('Edit houses','my_plugin'),
'new_item' => __('New houses','my_plugin'),
'view_item' => __('View houses','my_plugin'),
'search_items' => __('Search houses','my_plugin'),
'not_found' => __('No houses found','my_plugin'),
'not_found_in_trash'=> __('No houses found in Trash','my_plugin'),
'parent_item_colon' => '' ,
'all_items' => __( 'All houses' ,'my_plugin')
);
$args = array(
'labels' => $labels,
'public' => true,
'exclude_from_search'=> false,
'show_ui' => true,
'capability_type' => 'post',
'hierarchical' => false,
'rewrite' => array('slug'=>'houses', 'with_front' => true ),
'query_var' => false,
'menu_position' => null,
'supports' => array('title', 'thumbnail', 'page-attributes')
);
register_post_type('houses',$args);
}
add_action('init', 'register_cpt_houses');
}
function register_feature_taxonomy() {
$labels = array(
'name' => _x( 'Features', 'taxonomy general name', 'my_plugin' ),
'singular_name' => _x('Features', 'taxonomy singular name', 'my_plugin'),
'search_items' => __('Search Feature', 'my_plugin'),
'popular_items' => __('Common Features', 'my_plugin'),
'all_items' => __('All Features', 'my_plugin'),
'edit_item' => __('Edit Feature', 'my_plugin'),
'update_item' => __('Update Feature', 'my_plugin'),
'add_new_item' => __('Add new Feature', 'my_plugin'),
'new_item_name' => __('New Feature:', 'my_plugin'),
'add_or_remove_items' => __('Remove Feature', 'my_plugin'),
'choose_from_most_used' => __('Choose from common Feature', 'my_plugin'),
'not_found' => __('No Feature found.', 'my_plugin'),
'menu_name' => __('Features', 'my_plugin'),
);
$args = array(
'hierarchical' => false,
'labels' => $labels,
'show_ui' => true,
);
register_taxonomy('house_feature','houses', $args);
}
add_action( 'house_feature_add_form_fields', 'add_feature_group_field', 10, 2 );
function add_feature_group_field($taxonomy) {
global $feature_groups;
?><div class="form-field term-group">
<label for="featuret-group"><?php _e('Feature Group', 'my_plugin'); ?></label>
<select class="postform" id="equipment-group" name="feature-group">
<option value="-1"><?php _e('none', 'my_plugin'); ?></option><?php foreach ($feature_groups as $_group_key => $_group) : ?>
<option value="<?php echo $_group_key; ?>" class=""><?php echo $_group; ?></option>
<?php endforeach; ?>
</select>
</div><?php
}
add_action( 'created_house_feature', 'save_feature_meta', 10, 2 );
function save_feature_meta( $term_id, $tt_id ){
if( isset( $_POST['feature-group'] ) && '' !== $_POST['feature-group'] ){
$group = sanitize_title( $_POST['feature-group'] );
add_term_meta( $term_id, 'feature-group', $group, true );
}
}
add_action( 'house_feature_edit_form_fields', 'edit_feature_group_field', 10, 2 );
function edit_feature_group_field( $term, $taxonomy ){
global $feature_groups;
// get current group
$feature_group = get_term_meta( $term->term_id, 'feature-group', true );
?><tr class="form-field term-group-wrap">
<th scope="row"><label for="feature-group"><?php _e( 'Feature Group', 'my_plugin' ); ?></label></th>
<td><select class="postform" id="feature-group" name="feature-group">
<option value="-1"><?php _e( 'none', 'my_plugin' ); ?></option>
<?php foreach( $feature_groups as $_group_key => $_group ) : ?>
<option value="<?php echo $_group_key; ?>" <?php selected( $feature_group, $_group_key ); ?>><?php echo $_group; ?></option>
<?php endforeach; ?>
</select></td>
</tr><?php
}
add_action( 'edited_house_feature', 'update_feature_meta', 10, 2 );
function update_feature_meta( $term_id, $tt_id ){
if( isset( $_POST['feature-group'] ) && '' !== $_POST['feature-group'] ){
$group = sanitize_title( $_POST['feature-group'] );
update_term_meta( $term_id, 'feature-group', $group );
}
}
add_filter('manage_edit-house_feature_columns', 'add_feature_group_column' );
function add_feature_group_column( $columns ){
$columns['feature_group'] = __( 'Group', 'my_plugin' );
return $columns;
}
add_filter('manage_house_feature_custom_column', 'add_feature_group_column_content', 10, 3 );
function add_feature_group_column_content( $content, $column_name, $term_id ){
global $feature_groups;
if( $column_name !== 'feature_group' ){
return $content;
}
$term_id = absint( $term_id );
$feature_group = get_term_meta( $term_id, 'feature-group', true );
if( !empty( $feature_group ) ){
$content .= esc_attr( $feature_groups[ $feature_group ] );
}
return $content;
}
add_filter( 'manage_edit-house_feature_sortable_columns', 'add_feature_group_column_sortable' );
function add_feature_group_column_sortable( $sortable ){
$sortable[ 'feature_group' ] = 'feature_group';
return $sortable;
}
?>
What am I doing wrong?
If you need to export the data in termmeta table then try this plugin to export the termmeta data in separate XML file.
Export custom post type will only get you connection between the taxonomy ID and Post exported.
To get the Meta data of that taxonomy try this plugin It will provide you a XML containing all additional entries of that Taxonomy you can import that too
https://wordpress.org/plugins/wp-export-categories-taxonomies/
You will find this in Tools -> Wp Export Cats & Taxs
Select the Taxonomy in custom post types you want to export ..

Wordpress shortcode issues with output

Hi I am trying to workout how to use shortcodes on a plugin but I am stuck with this .. Its a plugin I found on http://www.wpbeginner.com/wp-tutorials/how-to-add-rotating-testimonials-in-wordpress/
It is working a little but not outputting the code correctly and not sure why this is happening.
I Have upgraded the code and removed the css and jquery code as I will add this separate files..
Any help will be great!
<?php
/*
Plugin Name: Shortcode test
Version: 0.1
Plugin URI: http://www.websiteplugin.com/
Description: Adding theatre edits to the resume page
Author: Auther name
Author URI: http://www.websiteauther.com/
*/
add_action( 'init', 'wpb_register_cpt_testimonial' );
function wpb_register_cpt_testimonial() {
$labels = array(
'name' => _x( 'Testimonials', 'testimonial' ),
'singular_name' => _x( 'testimonial', 'testimonial' ),
'add_new' => _x( 'Add New', 'testimonial' ),
'add_new_item' => _x( 'Add New testimonial', 'testimonial' ),
'edit_item' => _x( 'Edit testimonial', 'testimonial' ),
'new_item' => _x( 'New testimonial', 'testimonial' ),
'view_item' => _x( 'View testimonial', 'testimonial' ),
'search_items' => _x( 'Search Testimonials', 'testimonial' ),
'not_found' => _x( 'No testimonials found', 'testimonial' ),
'not_found_in_trash' => _x( 'No testimonials found in Trash', 'testimonial' ),
'parent_item_colon' => _x( 'Parent testimonial:', 'testimonial' ),
'menu_name' => _x( 'Testimonials', 'testimonial' ),
);
$args = array(
'labels' => $labels,
'hierarchical' => false,
'supports' => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'custom-fields', 'revisions' ),
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_nav_menus' => true,
'publicly_queryable' => true,
'exclude_from_search' => false,
'has_archive' => true,
'query_var' => true,
'can_export' => true,
'rewrite' => true,
'capability_type' => 'post'
);
register_post_type( 'testimonial', $args );
}
$key = "testimonial";
$meta_boxes = array(
"person-name" => array(
"name" => "person-name",
"title" => "Person's Name",
"description" => "Enter the name of the person who gave you the testimonial."),
"position" => array(
"name" => "position",
"title" => "Position in Company",
"description" => "Enter their position in their specific company."),
"company" => array(
"name" => "company",
"title" => "Company Name",
"description" => "Enter the client Company Name"),
"link" => array(
"name" => "link",
"title" => "Client Link",
"description" => "Enter the link to client's site, or you can enter the link to your portfolio page where you have the client displayed.")
);
function wpb_create_meta_box() {
global $key;
if( function_exists( 'add_meta_box' ) ) {
add_meta_box( 'new-meta-boxes', ucfirst( $key ) . ' Information', 'display_meta_box', 'testimonial', 'normal', 'high' );
}
}
function display_meta_box() {
global $post, $meta_boxes, $key;
?>
<div class="form-wrap">
<?php
wp_nonce_field( plugin_basename( __FILE__ ), $key . '_wpnonce', false, true );
foreach($meta_boxes as $meta_box) {
$data = get_post_meta($post->ID, $key, true);
?>
<div class="form-field form-required">
<label for="<?php echo $meta_box[ 'name' ]; ?>"><?php echo $meta_box[ 'title' ]; ?></label>
<input type="text" name="<?php echo $meta_box[ 'name' ]; ?>" value="<?php echo (isset($data[ $meta_box[ 'name' ] ]) ? htmlspecialchars( $data[ $meta_box[ 'name' ] ] ) : ''); ?>" />
<p><?php echo $meta_box[ 'description' ]; ?></p>
</div>
<?php } ?>
</div>
<?php
}
function wpb_save_meta_box( $post_id ) {
global $post, $meta_boxes, $key;
foreach( $meta_boxes as $meta_box ) {
if (isset($_POST[ $meta_box[ 'name' ] ])) {
$data[ $meta_box[ 'name' ] ] = $_POST[ $meta_box[ 'name' ] ];
}
}
if (!isset($_POST[ $key . '_wpnonce' ]))
return $post_id;
if ( !wp_verify_nonce( $_POST[ $key . '_wpnonce' ], plugin_basename(__FILE__) ) )
return $post_id;
if ( !current_user_can( 'edit_post', $post_id ))
return $post_id;
update_post_meta( $post_id, $key, $data );
}
add_action( 'admin_menu', 'wpb_create_meta_box' );
add_action( 'save_post', 'wpb_save_meta_box' );
function wpb_display_testimonials() {
$return_string .= "<div id=\"testimonials\">";
$args = array( 'post_type' => 'testimonial', 'posts_per_page' => 100, 'orderby' => 'menu_order', 'order' => 'ASC' );
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post();
$data = get_post_meta( $loop->post->ID, 'testimonial', true );
static $count = 0;
if ($count == "1") {
$pn_data = $data[ 'person-name' ];
$p_data = $data[ 'position' ];
$l_data = $data[ 'link' ];
$c_data = $data[ 'company' ];
$con_the = get_the_content( $more_link_text, $stripteaser );
$return_string .= '<div class="slide" style="display: none">
<div class="client-contact-info">'; $return_string .= $pn_data; $return_string .=', '; $return_string .= $p_data; $return_string .=', '; $return_string .= $c_data ; $return_string .='</div>';
$return_string .= '<div class="clear"></div>
<div class="testimonial-quote">'; $return_string .= $con_the; $return_string .='</div>
</div>';
}
else {
$pn_data = $data[ 'person-name' ];
$p_data = $data[ 'position' ];
$l_data = $data[ 'link' ];
$c_data = $data[ 'company' ];
$con_the = get_the_content( $more_link_text, $stripteaser );
$return_string .= '<div class="slide" >
<div class="client-contact-info">';
$return_string .= $pn_data;
$return_string .=', ';
$return_string .= $p_data;
$return_string .=', <a href="';
$return_string .= $l_data;
$return_string .='" title="';
$return_string .= $c_data ; $return_string .= '">';
$return_string .= $c_data ; $return_string .='</a></div>';
$return_string .= '<div class="clear"></div><div class="testimonial-quote">';
$return_string .= $con_the;
$return_string .='</div></div>';
$count++;
}
endwhile;
endif;
$return_string .='</div>';
return $return_string;
}
function register_shortcodes(){
add_shortcode('testme', 'wpb_display_testimonials');
}
add_action( 'init', 'register_shortcodes');
?>
If you look at the Shortcode API "Shortcode handlers ... they accept parameters (attributes) and return a result (the shortcode output)." in your function wpb_display_testimonials() EVERYTHING you want to return should be inside the value of $return_string .. the echo statements and the inline JS can't be used as you have it.
So instead of
?> <div> misc html </div> <?
you want to do something more like:
$return_string += '<div> misc html </div>';
you could also use output buffering though given you are already assembling $return_string best to use that and get it working then you can refactor later.

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