Wordpress shortcode issues with output - wordpress

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.

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.

Can't display all custom taxonomy values

This is my code to display all taxonomy values. It works but shows only first value and twice. How to stop duplicate this value?
// Register Custom Taxonomy-poleca
function recommend_custom_taxonomy_Item() {
$labels = array(
'name' => 'Poleca',
'singular_name' => 'Poleca',
'menu_name' => 'Poleca',
'all_items' => 'Wszyscy polecający',
'parent_item' => 'Parent Brand',
'parent_item_colon' => 'Parent Brand:',
'new_item_name' => 'Nowy Polecający',
'add_new_item' => 'Dodaj nowego polecającego',
'edit_item' => 'Edytuj polecającą',
'update_item' => 'Update polecający',
'separate_items_with_commas' => 'Oddziel przecinkami',
'search_items' => 'Szukaj recommend',
'add_or_remove_items' => 'Add or remove polecającego',
'choose_from_most_used' => 'Choose from the most used Brands',
);
$args = array(
'labels' => $labels,
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'show_in_nav_menus' => true,
'show_tagcloud' => true,
);
register_taxonomy( 'recommend', 'product', $args );
}
add_action( 'init', 'recommend_custom_taxonomy_item');
add_action( 'woocommerce_before_add_to_cart_button', 'add_recommend_term');
function add_recommend_term() {
$terms = get_the_terms(get_the_ID(), 'recommend');
$author_image = wp_get_attachment_image_src($img_id );
foreach ( $terms as $term ) {
if (!is_wp_error($terms) && !empty($terms)) { ?>
<div class="recommend-name"><?php echo esc_html($terms[0]->name); ?> <br><?php echo esc_html($terms[0]->description);?></div>
<?php }
}
Just replace your above code's parts with follows snippet -
add_action( 'woocommerce_before_add_to_cart_button', 'add_recommend_term');
function add_recommend_term() {
$terms = get_the_terms( get_the_ID(), 'recommend' );
if ( $terms && ! is_wp_error( $terms ) ) :
foreach ( $terms as $term ) {
?>
<div class="recommend-name">
<a href="<?php echo esc_url( get_term_link( $term ) ); ?>">
<?php echo esc_html( $term->name ); ?><br><?php echo esc_html( $term->description ); ?>
</a>
</div>
<?php }
endif;
}

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 - Is it possible to add multiple text fields in one row with CMB2?

Using CMB2 we are able to create metaboxes for various post types. Right now, by default, every added custom field will be separated with new row.
For a better usability I would need to add some text fields next to each other, like on the image bellow:
Is that even possible with CMB2?
Code Im using right now is:
$cmb->add_field( array(
'name' => 'Test Text Medium',
'desc' => 'Street',
'default' => '',
'id' => 'street',
'type' => 'text_medium',
) );
In this case cmb has the great feature for creating custom field type.
Hope this link will help you https://github.com/WebDevStudios/CMB2/wiki/Adding-your-own-field-types#use-the-field-in-your-template
you can use multiple fields inside a custom field
Here is the simple code for creating custom field with multiple fields
function cmb2_render_address_field_callback( $field, $value, $object_id, $object_type, $field_type ) {
$value = wp_parse_args( $value, array(
'street1' => '',
'street2' => '',
'street3' => ''
) );
?>
<div class="alignleft"><p><label for="<?php echo $field_type->_id( '_street1' ); ?>">Street</label></p>
<?php echo $field_type->input( array(
'class' => 'cmb_text_small',
'name' => $field_type->_name( '[street1]' ),
'id' => $field_type->_id( '_street1' ),
'type' => 'street1',
'value' => $value['street1'],
) ); ?>
</div>
<div class="alignleft"><p><label for="<?php echo $field_type->_id( '_street2' ); ?>'">Street</label></p>
<?php echo $field_type->input( array(
'class' => 'cmb_text_small',
'name' => $field_type->_name( '[street2]' ),
'id' => 'street2',
'type' => 'text',
'value' => $value['street2'],
) ); ?>
</div>
<div class="alignleft"><p><label for="<?php echo $field_type->_id( '_street3' ); ?>'">Street</label></p>
<?php echo $field_type->input( array(
'class' => 'cmb_text_small',
'name' => $field_type->_name( '[street3]' ),
'id' => $field_type->_id( '_street3' ),
'type' => 'time',
'value' => $value['street3'],
) ); ?>
</div>
<?php
echo $field_type->_desc( true );
}
add_filter( 'cmb2_render_address', 'cmb2_render_address_field_callback', 10, 5 );
Create your own field type as follows
function cmb2_get_state_options( $value = false ) {
$state_list = array( 'AL'=>'Alabama','AK'=>'Alaska','AZ'=>'Arizona','AR'=>'Arkansas','CA'=>'California','CO'=>'Colorado','CT'=>'Connecticut','DE'=>'Delaware','DC'=>'District Of Columbia','FL'=>'Florida','GA'=>'Georgia','HI'=>'Hawaii','ID'=>'Idaho','IL'=>'Illinois','IN'=>'Indiana','IA'=>'Iowa','KS'=>'Kansas','KY'=>'Kentucky','LA'=>'Louisiana','ME'=>'Maine','MD'=>'Maryland','MA'=>'Massachusetts','MI'=>'Michigan','MN'=>'Minnesota','MS'=>'Mississippi','MO'=>'Missouri','MT'=>'Montana','NE'=>'Nebraska','NV'=>'Nevada','NH'=>'New Hampshire','NJ'=>'New Jersey','NM'=>'New Mexico','NY'=>'New York','NC'=>'North Carolina','ND'=>'North Dakota','OH'=>'Ohio','OK'=>'Oklahoma','OR'=>'Oregon','PA'=>'Pennsylvania','RI'=>'Rhode Island','SC'=>'South Carolina','SD'=>'South Dakota','TN'=>'Tennessee','TX'=>'Texas','UT'=>'Utah','VT'=>'Vermont','VA'=>'Virginia','WA'=>'Washington','WV'=>'West Virginia','WI'=>'Wisconsin','WY'=>'Wyoming' );
$state_options = '';
foreach ( $state_list as $abrev => $state ) {
$state_options .= '<option value="'. $abrev .'" '. selected( $value, $abrev, false ) .'>'. $state .'</option>';
}
return $state_options;
}
function cmb2_render_address_field_callback( $field, $value, $object_id, $object_type, $field_type ) {
// make sure we specify each part of the value we need.
$value = wp_parse_args( $value, array(
'address-1' => '',
'address-2' => '',
'city' => '',
'state' => '',
'zip' => '',
) );
?>
<div><p><label for="<?php echo $field_type->_id( '_address_1' ); ?>">Address 1</label></p>
<?php echo $field_type->input( array(
'name' => $field_type->_name( '[address-1]' ),
'id' => $field_type->_id( '_address_1' ),
'value' => $value['address-1'],
'desc' => '',
) ); ?>
</div>
<div><p><label for="<?php echo $field_type->_id( '_address_2' ); ?>'">Address 2</label></p>
<?php echo $field_type->input( array(
'name' => $field_type->_name( '[address-2]' ),
'id' => $field_type->_id( '_address_2' ),
'value' => $value['address-2'],
'desc' => '',
) ); ?>
</div>
<div class="alignleft"><p><label for="<?php echo $field_type->_id( '_city' ); ?>'">City</label></p>
<?php echo $field_type->input( array(
'class' => 'cmb_text_small',
'name' => $field_type->_name( '[city]' ),
'id' => $field_type->_id( '_city' ),
'value' => $value['city'],
'desc' => '',
) ); ?>
</div>
<div class="alignleft"><p><label for="<?php echo $field_type->_id( '_state' ); ?>'">State</label></p>
<?php echo $field_type->select( array(
'name' => $field_type->_name( '[state]' ),
'id' => $field_type->_id( '_state' ),
'options' => cmb2_get_state_options( $value['state'] ),
'desc' => '',
) ); ?>
</div>
<div class="alignleft"><p><label for="<?php echo $field_type->_id( '_zip' ); ?>'">Zip</label></p>
<?php echo $field_type->input( array(
'class' => 'cmb_text_small',
'name' => $field_type->_name( '[zip]' ),
'id' => $field_type->_id( '_zip' ),
'value' => $value['zip'],
'type' => 'number',
'desc' => '',
) ); ?>
</div>
<br class="clear">
<?php
echo $field_type->_desc( true );
}
add_filter( 'cmb2_render_address', 'cmb2_render_address_field_callback', 10, 5 );
To register a new type use below code
...
'fields' => array(
array(
'name' => 'Address',
'desc' => 'Custom Address Field',
'id' => '_cmb2_person_address',
'type' => 'address',
),
),
...
and for displaying we can use as follows
$post_id = get_the_ID();
$address = get_post_meta( $post_id, '_cmb2_person_address', 1 );
// Set default values for each address key
$address = wp_parse_args( $address, array(
'address-1' => '',
'address-2' => '',
'city' => '',
'state' => '',
'zip' => '',
) );
?>
<p><strong>Address:</strong> <?php echo esc_html( $address['address-1'] ); ?></p>
<?php if ( $address['address-2'] ) : ?>
<p><strong>Address 2:</strong> <?php echo esc_html( $address['address-2'] ); ?></p>
<?php endif; ?>
<p><strong>City:</strong> <?php echo esc_html( $address['city'] ); ?></p>
<p><strong>State:</strong> <?php echo esc_html( $address['state'] ); ?></p>
<p><strong>Zip:</strong> <?php echo esc_html( $address['zip'] ); ?></p>
For more details check CMB2 Docs

shortcode from Custom post in wordpress

I want to show my custom post using shortcode
my custom post code is below-
/Custom Post/
add_action( 'init', 'create_post_type' );
function create_post_type() {
register_post_type( 'service_items',
array(
'labels' => array(
'name' => __( 'Service Items' ),
'singular_name' => __( 'Service Items' ),
'add_new' => __( 'Add New' ),
'add_new_item' => __( 'Add New Service Items' ),
'edit_item' => __( 'Edit Service Items' ),
'new_item' => __( 'New Service Items' ),
'view_item' => __( 'View Service Items' ),
'not_found' => __( 'Sorry, we couldn\'t find the Service Items you are looking for.' )
),
'public' => true,
'publicly_queryable' => true,
'exclude_from_search' => true,
'menu_position' => 14,
'has_archive' => false,
'hierarchical' => false,
'capability_type' => 'page',
'rewrite' => array( 'slug' => 'custompost_id' ),
'supports' => array( 'title', 'editor', 'custom-fields','thumbnail' )
)
);
}
And Shortcode code is below -
function service_item_shortcode() {
$args = array(
'post_type' => 'service_items',
'order' => 'DESC',
'posts_per_page'=> -1
);
$service_items = new WP_Query( $args );
if( $service_items->have_posts() ):
while ( $service_items->have_posts() ) : $service_items->the_post();
$service_output = '<div class="span3 serv">';
$service_output .='<div class="serv-img">' ;
$service_output .=get_the_post_thumbnail( $service_items->post->ID, service-image) ;
$service_output .='</div>';
$service_output .= '<h3>' . get_the_title() . '</h3> ';
$service_output .= '<p>' . get_the_content() . '</p> ';
$service_output .= '</div>';
endwhile;
endif;
return $service_output;
}
add_shortcode( 'service_item', 'service_item_shortcode' );
I want to show on my post 4 custom post items per page.
But when I put [service-item] shortcode output only show 1 post.
I need 4 post per page. Please help.
You should write the output from all posts in a variable, instead of resetting the variable on each iteration. To do this, define an empty variable before the loop, and simply add to it all of the output of each post. Here is the changed code that should work for you (untested):
function service_item_shortcode() {
$service_output = '';
$paged = !empty($_GET['service_item_page']) ? absint($_GET['service_item_page']) : 1;
if (!$paged) {
$paged = 1;
}
$args = array(
'post_type' => 'service_items',
'order' => 'DESC',
'posts_per_page'=> 4,
'paged' => $paged
);
$service_items = new WP_Query( $args );
if( $service_items->have_posts() ):
while ( $service_items->have_posts() ) : $service_items->the_post();
$service_output .= '<div class="span3 serv">';
$service_output .= '<div class="serv-img">' ;
$service_output .= get_the_post_thumbnail( get_the_ID(), 'service-image');
$service_output .= '</div>';
$service_output .= '<h3>' . get_the_title() . '</h3> ';
$service_output .= '<p>' . get_the_content() . '</p> ';
$service_output .= '</div>';
endwhile;
endif;
if ($service_items->max_num_pages > 1) {
$service_output .= '<div class="pagination">';
for($i = 1; $i <= $service_items->max_num_pages; $i++) {
$service_output .= '' . $i . ' ';
}
$service_output .= '</div>';
}
wp_reset_postdata();
return $service_output;
}
add_shortcode( 'service_item', 'service_item_shortcode' );

Resources