I am using WooCommerce plugin in Wordpress. In that plugin I need to add text input for each product where in clients can fill in the additional product details.
The problem I am facing is that whenever I Add Text Attribute, it changes to a select box. Please suggest some solution. Thanks!
Do you mean that your clients should have this text input field available on frontend?
If it's just backend, you can add this to your functions.php:
if (is_admin()){
// Add the Meta Box
function add_textfield() {
add_meta_box(
'textfield', // $id
'Custom textfield', // $title
'show_textfield_backend', // $callback
'product', // $page
'normal', // $context
'high' // $priority
);
}
add_action('add_meta_boxes', 'add_textfield');
// The Callback
function show_textfield_backend() {
global $post;
global $wpdb;
$meta = get_post_meta($post->ID, 'textfield', true);
// Use nonce for verification
echo '<input type="hidden" name="textfield_nonce" value="'.wp_create_nonce(basename(__FILE__)).'" />';
_e('Custom textfield: ');
echo '<input type="text" placeholder="text" id="textfield" class="textfield" name="textfield" ', $meta ? " value='$meta'" : "",' />';
}
// Save the Data
function save_textfield($post_id) {
global $wpdb;
// verify nonce
if (!wp_verify_nonce($_POST['textfield_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;
}
if ( !wp_is_post_revision( $post_id ) ) {
$textfield = $_POST['textfield'];
update_post_meta($post_id, 'textfield', $textfield);
}
}
add_action('save_post', 'save_textfield');
}
Related
I have a problem with updating my custom meta box in wordpress for a custom post news. I have made a meta box checkbox so I could decide if the post is featured or not. If the checkbox is checked then isFeatured = 1. Until this part it works, the problem is when after sometime I wan't to edit the post and deselect the checkbox. After updating the post the checkbox is checked all the time.
The database: meta_key | meta_value ---- > news_details | a:1:{s:10:"isFeatured";s:1:"1";}
This is how my code looks:
function add_news_details_meta_box() {
add_meta_box(
'news_details_meta_box', // $id
'Checkbox', // $title
'show_news_details_meta_box', // $callback
'news', // $screen
'normal', // $context
'high' // $priority
);
}
add_action( 'add_meta_boxes', 'add_news_details_meta_box' );
function show_news_details_meta_box() {
global $post;
$meta = get_post_meta( $post->ID, 'news_details', true ); ?>
<input type="hidden" name="news_details_meta_box_nonce" value="<?php echo wp_create_nonce( basename(__FILE__) ); ?>">
<p>
<label for="news_details[isFeatured]">Is this post featured?
<input type="checkbox" name="news_details[isFeatured]" value="1" <?php if (is_array($meta) && $meta['isFeatured'] === '1' ) { echo 'checked';} else { echo 'Unchecked';}?>>
</label>
</p>
<?php
}
function save_news_details_meta( $post_id ) {
// verify nonce
if ( !wp_verify_nonce( $_POST['news_details_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;
}
}
$old = get_post_meta( $post_id, 'news_details', true );
$new = $_POST['news_details'];
if ( $new && $new !== $old ) {
update_post_meta( $post_id, 'news_details', $new );
} elseif ( '' === $new && $old ) {
delete_post_meta( $post_id, 'news_details', $old );
}
}
add_action( 'save_post', 'save_news_details_meta' );
Could you explain to me what's wrong with updating the checkbox after sometime?
I think you should check the if condition. The way I got your description, the $meta['isFeatured'] === '1' always becomes true. You set the value to 1 in the input tag. So on save the value of 1 gets saved to the field I guess. On next load you are checking with an if, if the $meta['isFeatured'] is 1, so this is always true.
You could check if the checkbox in the form is checked with:
isset($_POST['name_of_your_checkbox_input'])
If it is set, you save the value of 1. If not, you stay at the pre defined value of 0.
What worked for me in this case was changing } elseif ( '' === $new && $old ) { to } else ( '' === $new && $old ) {
i am trying to implement a simple checkbox on the page, in order to dynamically add a Html chunk in case the user choses it, but i am unable to save the post_meta to perform this task, can someone help me? The value taken from this checkbox input is not been save on the post meta information.
This is what i got so far on my functions.php
function wporg_add_custom_box(){
$screens = ['page', 'wporg_cpt'];
foreach ($screens as $screen) {
add_meta_box(
'wporg_box_id', // Unique ID
'Entra in Flee Block', // Box title
'wporg_custom_box_html', // Content callback, must be of type callable
$screen, // Post type
'side'
);
}
}
add_action('add_meta_boxes', 'wporg_add_custom_box');
function wporg_custom_box_html($post){
$value = get_post_meta($post->ID, '_wporg_meta_key', true);
?>
<label for="wporg_field">Add "Entra in Flee" block to page</label>
</br>
<input type="checkbox" name="wporg_field" id="wporg_field" class="postbox">
<?php
}
function wporg_save_postdata($post_id){
if (array_key_exists('wporg_field', $_POST)) {
update_post_meta(
$post_id,
'_wporg_meta_key',
$_POST['wporg_field']
);
}
}
add_action('save_post', 'wporg_save_postdata');
You don't use the $value on wp_cusotm_box_html function.
I think it should be somthing like this:
function wporg_add_custom_box()
{
$screens = ['page', 'wporg_cpt'];
foreach ($screens as $screen) {
add_meta_box(
'wporg_box_id', // Unique ID
'Entra in Flee Block', // Box title
'wporg_custom_box_html', // Content callback, must be of type callable
$screen, // Post type
'side'
);
}
}
add_action('add_meta_boxes', 'wporg_add_custom_box');
function wporg_custom_box_html($post)
{
$value = get_post_meta($post->ID, '_wporg_meta_key', true) ? 'checked' : '';
?>
<label for="wporg_field">Add "Entra in Flee" block to page</label>
</br>
<input type="checkbox" name="wporg_field" id="wporg_field" class="postbox" <?php echo $value; ?>>
<?php
}
function wporg_save_postdata($post_id)
{
if (array_key_exists('wporg_field', $_POST)) {
update_post_meta(
$post_id,
'_wporg_meta_key',
$_POST['wporg_field']
);
} else {
delete_post_meta(
$post_id,
'_wporg_meta_key'
);
}
}
add_action('save_post', 'wporg_save_postdata');
I would like to add a meta box to a custom post type that works like the product gallery meta box that Woocommerce uses. I actually have Woocommerce installed on this project.
I found the code that Woocommerce uses to create the product gallery meta box, and I can get the meta box to display, but the jQuery is not there to pull up the media lightbox that Wordpress uses to add images. I don't know if there is a hook I need to add or if I should enqueue a script?
Here is what I have so far (based on the WooCommerce code but altered for my use)
<?php
function add_mtg_meta_boxes() {
add_meta_box('mtg_hotel_gallery_meta_box', 'Hotel Gallery', 'setup_mtg_hotel_gallery_meta_box', 'meeting', 'side', 'low');
}
add_action('add_meta_boxes', 'add_mtg_meta_boxes');
function setup_mtg_hotel_gallery_meta_box($post) {
echo '<input type="hidden" name="mtg_hotel_gallery_meta_box_nonce" value="'. wp_create_nonce('mtg_hotel_gallery_meta_box'). '" />';
?>
<div id="product_images_container">
<ul class="product_images">
<?php
if ( metadata_exists( 'post', $post->ID, '_product_image_gallery' ) ) {
$product_image_gallery = get_post_meta( $post->ID, '_product_image_gallery', true );
} else {
// Backwards compatibility.
$attachment_ids = get_posts( 'post_parent=' . $post->ID . '&numberposts=-1&post_type=attachment&orderby=menu_order&order=ASC&post_mime_type=image&fields=ids&meta_key=_woocommerce_exclude_image&meta_value=0' );
$attachment_ids = array_diff( $attachment_ids, array( get_post_thumbnail_id() ) );
$product_image_gallery = implode( ',', $attachment_ids );
}
$attachments = array_filter( explode( ',', $product_image_gallery ) );
$update_meta = false;
$updated_gallery_ids = array();
if ( ! empty( $attachments ) ) {
foreach ( $attachments as $attachment_id ) {
$attachment = wp_get_attachment_image( $attachment_id, 'thumbnail' );
// if attachment is empty skip
if ( empty( $attachment ) ) {
$update_meta = true;
continue;
}
echo '<li class="image" data-attachment_id="' . esc_attr( $attachment_id ) . '">
' . $attachment . '
<ul class="actions">
<li>' . __( 'Delete', 'woocommerce' ) . '</li>
</ul>
</li>';
// rebuild ids to be saved
$updated_gallery_ids[] = $attachment_id;
}
// need to update product meta to set new gallery ids
if ( $update_meta ) {
update_post_meta( $post->ID, '_product_image_gallery', implode( ',', $updated_gallery_ids ) );
}
}
?>
</ul>
<input type="hidden" id="product_image_gallery" name="product_image_gallery" value="<?php echo esc_attr( $product_image_gallery ); ?>" />
</div>
<p class="add_product_images hide-if-no-js">
<?php _e( 'Add product gallery images', 'woocommerce' ); ?>
</p>
<?php
}
function save_mtg_hotel_gallery_meta_box($post_id) {
// check nonce
if (!isset($_POST['mtg_gallery_meta_box_nonce']) || !wp_verify_nonce($_POST['mtg_gallery_meta_box_nonce'], 'mtg_gallery_meta_box')) {
return $post_id;
}
// check capabilities
if ('meeting' == $_POST['post_type']) {
if (!current_user_can('edit_post', $post_id)) {
return $post_id;
}
} elseif (!current_user_can('edit_page', $post_id)) {
return $post_id;
}
// exit on autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return $post_id;
}
$attachment_ids = isset( $_POST['product_image_gallery'] ) ? array_filter( explode( ',', wc_clean( $_POST['product_image_gallery'] ) ) ) : array();
update_post_meta( $post_id, '_product_image_gallery', implode( ',', $attachment_ids ) );
}
add_action('save_post', 'save_mtg_hotel_gallery_meta_box');
?>
First To Enable the Wordpress Wp Media Uploader you have to enqueue the media js by using wp_enqueue_media(); inside you functions.php admin_enqueue_scripts hook,
function enqueue_media_uploader() {
wp_enqueue_media();
}
add_action( 'admin_enqueue_scripts', 'enqueue_media_uploader' );
and then you have to assign an id to your anchor which clicked media.uploader
will pop up.Like this...
<?php _e( 'Add product gallery images', 'woocommerce' ); ?>
And then to bind the onclick listener to add_product_image id add this line of code to your custom js file...
jQuery('#add_product_image').click(function(e) {
e.preventDefault();
var image = wp.media({
title: 'Upload Image',
multiple: false
}).open()
.on('select', function(e){
var uploaded_image = image.state().get('selection').first();
var image_url = uploaded_image.toJSON().url;
var image_id = uploaded_image.toJSON().id;
});
});
Here image_url var is uploaded or selected image src url and image_id var is id of the image or attachment.
I have a plugin that adds a meta box with file upload form, the plugin works perfectly, displays the link of the image in the meta box (View Image), load the file, and once published the post, it views in the theme. (in the example I'm using an image file):
<?php
/* Plugin Name: Custom Meta Upload Template*/
add_action('post_edit_form_tag', 'post_edit_form_tag');
function post_edit_form_tag() {
echo ' enctype="multipart/form-data"';
}
function custom_upload() {
add_meta_box( 'meta_upload', __( 'Upload Image', 'meta_upload_domain' ),'meta_upload_callback', 'post' );}
add_action( 'add_meta_boxes', 'custom_upload' );
function meta_upload_callback( $post ) {
global $post;
$custom = get_post_custom($post->ID);
$download_image01 = get_post_meta($post->ID, '_image01', true);
echo '<p><label for="document_file">Upload document:</label><br />';
echo '<input type="file" name="document_file" id="document_file" /></p>';
echo '</p>';
if(!empty($download_image01) && $download_image01 != '0') {
echo '<p>View Image</p>';
}
}
function meta_upload_save( $post_id ) {
global $post;
if(strtolower($_POST['post_type']) === 'page') {
if(!current_user_can('edit_page', $post_id)) {
return $post_id;
}
}
else {
if(!current_user_can('edit_post', $post_id)) {
return $post_id;
}
}
if(!empty($_FILES['document_file'])) {
$file = $_FILES['document_file'];
$upload = wp_handle_upload($file, array('test_form' => false));
if(!isset($upload['error']) && isset($upload['file'])) {
$title = $file['name'];
$ext = strrchr($title, '.');
$title = ($ext !== false) ? substr($title, 0, -strlen($ext)) : $title;
$attachment = array(
'post_mime_type' => 'image',
'post_title' => addslashes($title),
'post_content' => '',
'post_status' => 'inherit',
'post_parent' => $post->ID
);
$attach_key = '_image01';
$attach_id = wp_insert_attachment($attachment, $upload['file']);
$existing_download = (int) get_post_meta($post->ID, $attach_key, true);
if(is_numeric($existing_download)) {
wp_delete_attachment($existing_download);
}
update_post_meta($post->ID, $attach_key, $attach_id);
}
}
}
add_action( 'save_post', 'meta_upload_save' );
and he called the file in the theme:
<?php
$download_image01 = get_post_meta($post->ID, '_image01', true);
if(!empty($download_image01) && $download_image01 != '0') { ?>
<div class="section-content">
<img src="<?php echo wp_get_attachment_url($download_image01); ?>" alt="" />
</div>
<?php }?>
I repeat, the plugin works, but the problem is that I can not place a button or a checkbox that deletes the file when, for example, I want to edit the post, and delete the file, and of course the link "View Image" disappears
Any idea!!
Whenever you want to edit these fields echo the value of the custom fields look like this...
<input type="" value="<img src="<?php echo wp_get_attachment_url($download_image01); ?>" alt="" />">
When you edit the post it's get the value and show the uploaded image's to you.
I don't know if that can help, but I use this code to exclude Attachment when I delete a Custom Post:
add_action('before_delete_post', 'delete_all_attached_media');
function delete_all_attached_media($post_id)
{
if (get_post_type($post_id) == "your-custom-post-type") {
$attachments = get_attached_media('', $post_id);
foreach ($attachments as $attachment) {
wp_delete_attachment($attachment->ID, 'true');
}
}
}
I have a custom post type which has a custom taxonomy called "country". I want a drop-down list in the Dashboard -> Theme Option to select the term name under this taxonomy. So I have created the following function:
function featured_country($show_count = false, $country_array = array()) {
$countries = get_terms( 'category', 'hide_empty=0&fields=all' );
foreach ($countries as $countr) {
$country_array[$countr->term_id] = $countr->name;
}
return $country_array;
}
Then I call this function as follows:
$this->admin_option('Front Page Option',
'Featured country', 'featured_country',
'select', '',
array('options'=>$this->featured_country(true, array(''=>'Select Category')),
'help'=>'Some helping text')
);
Unfortunately this drop-down list displays nothing. But when I put the parameter of get_terms() as “category” or "link_category" it works.
I can not understand where is my problem. How can I solve this? Please help me.
Try out this code
function get_terms_dropdown($taxonomies, $args){
$myterms = get_terms($taxonomies, $args);
$output ="<select name='TAXONOMY SLUG'>";
foreach($myterms as $term){
$root_url = get_bloginfo('url');
$term_taxonomy=$term->taxonomy;
$term_slug=$term->slug;
$term_name =$term->name;
$link = $term_slug;
$output .="<option value='".$link."'>".$term_name."</option>";
}
$output .="</select>";
return $output;
}
(I took it from this forum thread)
Here's the example where Custom taxonomy" is courses" & custom post type for that is "help_lessions"
/*
* Set Selectbox for Custom taxonomy "courses" in admin panel
*/
function custom_meta_box() {
remove_meta_box('tagsdiv-courses', 'help_lessions', 'side');
add_meta_box('tagsdiv-courses', 'Course', 'Courses_meta_box', 'help_lessions', 'side');
}
add_action('add_meta_boxes', 'custom_meta_box');
/* Prints the taxonomy box content */
function courses_meta_box($post) {
$tax_name = 'courses';
$taxonomy = get_taxonomy($tax_name);
?>
<div class="tagsdiv" id="<?php echo $tax_name; ?>">
<div class="jaxtag">
<?php
// Use nonce for verification
wp_nonce_field(plugin_basename(__FILE__), 'courses_noncename');
$help_ids = wp_get_object_terms($post->ID, 'courses', array('fields' => 'ids'));
wp_dropdown_categories('taxonomy=courses&hide_empty=0&orderby=name&name=courses&show_option_none=Select Course&selected=' . $help_ids[0]);
?>
<p class="howto">Select your Course</p>
</div>
</div>
<?php
}
/* When the post is saved, saves our custom taxonomy */
function courses_save_postdata($post_id) {
// verify if this is an auto save routine.
// If it is our form has not been submitted, so we dont want to do anything
if (( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) || wp_is_post_revision($post_id))
return;
// verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
if (!wp_verify_nonce($_POST['courses_noncename'], plugin_basename(__FILE__)))
return;
// Check permissions
if ('help_lessions' == $_POST['post_type']) {
if (!current_user_can('edit_page', $post_id))
return;
}
else {
if (!current_user_can('edit_post', $post_id))
return;
}
// Now, we need to find and save the data
$help_id = $_POST['courses'];
$help = ( $help_id > 0 ) ? get_term($help_id, 'courses')->slug : NULL;
wp_set_object_terms($post_id, $help, 'courses');
}
add_action('save_post', 'courses_save_postdata');