Add a checkbox in the post meta box - wordpress

I want to add a checkbox in product post type. So i wrote the code
add_action( 'add_meta_boxes', 'smashing_add_post_meta_boxes' );
/* Create one or more meta boxes to be displayed on the post editor screen. */
function smashing_add_post_meta_boxes() {
add_meta_box(
'smashing-post-class', // Unique ID
esc_html__( 'Post Class', 'example' ), // Title
'smashing_post_class_meta_box', // Callback function
'product', // Admin page (or post type)
'side', // Context
'default' // Priority
);
}
/* Display the post meta box. */
function smashing_post_class_meta_box( $object, $box ) { ?>
<?php wp_nonce_field( basename( __FILE__ ), 'smashing_post_class_nonce' ); ?>
<p>
<label for="smashing-post-class"><?php _e( "Add a custom CSS class, which will be applied to WordPress' post class.", 'example' ); ?></label>
<br />
<input class="widefat" type="checkbox" name="smashing-post-class" id="smashing-post-class" value="<?php echo esc_attr( get_post_meta( $object->ID, 'smashing_post_class', true ) ); ?>" size="30" />What's New
</p>
<?php }
/* Save post meta on the 'save_post' hook. */
add_action( 'save_post', 'smashing_save_post_class_meta', 10, 2 );
/* Save the meta box's post metadata. */
function smashing_save_post_class_meta( $post_id, $post ) {
/* Verify the nonce before proceeding. */
if ( !isset( $_POST['smashing_post_class_nonce'] ) || !wp_verify_nonce( $_POST['smashing_post_class_nonce'], basename( __FILE__ ) ) )
return $post_id;
/* Get the post type object. */
$post_type = get_post_type_object( $post->post_type );
/* Check if the current user has permission to edit the post. */
if ( !current_user_can( $post_type->cap->edit_post, $post_id ) )
return $post_id;
/* Get the posted data and sanitize it for use as an HTML class. */
$new_meta_value = ( isset( $_POST['smashing-post-class'] ) ? sanitize_html_class( $_POST['smashing-post-class'] ) : '' );
/* Get the meta key. */
$meta_key = 'smashing_post_class';
/* Get the meta value of the custom field key. */
$meta_value = get_post_meta( $post_id, $meta_key, true );
/* If a new meta value was added and there was no previous value, add it. */
if ( $new_meta_value && '' == $meta_value )
add_post_meta( $post_id, $meta_key, $new_meta_value, true );
/* If the new meta value does not match the old value, update it. */
elseif ( $new_meta_value && $new_meta_value != $meta_value )
update_post_meta( $post_id, $meta_key, $new_meta_value );
/* If there is no new meta value but an old value exists, delete it. */
elseif ( '' == $new_meta_value && $meta_value )
delete_post_meta( $post_id, $meta_key, $meta_value );
}
How can i change the code to get the checkbox value and checked if someone check the checkbox before.
Here, i changed only the input box "text" to "checkbox". But i do not know what to do to create a single checkbox. Please help me. I am new in wordpress.

you prob need to assign a value for the checkbox. You might want to think what this value is if not already set.
value="<?php echo esc_attr( get_post_meta( $object->ID, 'smashing_post_class', true ) ); ?>"
on a new post this is not set. So you could do something like
value="<?php if ($x=get_post_meta( $object->ID, 'smashing_post_class', true ) ) {echo $x;}else{echo "whatever";} ?>"
You are already saving the value to post_meta(see $new_meta_value) so the code to set the value already pulls it from the database if it exists.
you might want to rethink the way you are doing the above. The checkbox value is always going to be the same from now on. You might as well set the value to whatever you want it to be right now. E.g.
<input type="checkbox" name="whatever" value="true"> select me for fun
you can access the posted value in your save meta box function
$value= $_POST['whatever'];
and save to post meta (a seperate database table for custom values and a few other values that dont fit wp_posts)
update_post_meta($post_id, '_keyname', $value);

Related

Custom Field created in add_meta_boxes reappearing itself again in the default Custom Metabox

I succeed in creating a metabox with custom field inside, and I restrict it to appear in a custom post type.
//define metabox
function product_info_en() {
add_meta_box( 'english_info', 'English Info', 'english_product_name_callback', array('product'), 'normal', 'high' );
}
//add to hook
add_action( 'add_meta_boxes', 'product_info_en' );
The code to display it in the product page:
// display in add product admin page
function english_product_name_callback( $post ) {
//ob_start();
$content = esc_attr( get_post_meta( get_the_ID(), 'product_desc_en', true ) );
//here goes the custom field
echo '<fieldset><div><label><b>English Product Name:</b></label><br/>';
echo '<input id="product_name_en" type="text" name="product_name_en" style="width:100%; margin:10px 0px"';
echo ' value="';
echo esc_attr( get_post_meta( get_the_ID(), 'product_desc_en', true ) );
echo '"></div></fieldset>';
//here goes the wp_editor
echo '<fieldset><div><label><b>English Product Content Info:</b></label><div><br/>';
echo '<div>';
wp_editor($content, 'product_desc_en', array(
'wpautop' => true,
'media_buttons' => true,
'textarea_rows' => 10
)
);
echo '</div></fieldset>';
}
Here goes the code that do the saving job:
//save
function enginfo_save_meta_box( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
if ( $parent_id = wp_is_post_revision( $post_id ) ) {
$post_id = $parent_id;
}
$fields = [
'product_name_en',
];
foreach ( $fields as $field ) {
if ( array_key_exists( $field, $_POST ) ) {
update_post_meta( $post_id, $field, sanitize_text_field( $_POST[$field] ) );
}
}
update_post_meta( $post_id,'product_desc_en', wp_kses_post( $_POST['product_desc_en'] ) );
}
add_action( 'save_post', 'enginfo_save_meta_box' );
However, the custom created field that supposed to be going only into the newly created metabox, will always show up in the default "custom field". And this happens to all post type.
As shown below, What could possibly be the issue here?
To hide and not show your custom fields there in default box, please prefix your custom fields with underscore _ , so product_desc_en will become _product_des_en
I mean the names of your custom fields should be prefixed with underscore and WordPress default custom metabox will ignore them and not show in WordPress default GUI, but you can use and display them in your own custom metaboxes by calling with there new Underscore prefixed names.

metabox checkbox value is not updating

data gets updated correctly in the the database. however, when i'm in WP, the checkboxes don't get the values correctly...they all show up as unchecked. any thoughts on how to do this.
Thanks in advance
/* Fire our meta box setup function on the post editor screen. */
add_action( 'load-post.php', 'smashing_post_meta_boxes_setup' );
add_action( 'load-post-new.php', 'smashing_post_meta_boxes_setup' );
/* Meta box setup function. */
function smashing_post_meta_boxes_setup() {
/* Add meta boxes on the 'add_meta_boxes' hook. */
add_action( 'add_meta_boxes', 'smashing_add_post_meta_boxes' );
/* Save post meta on the 'save_post' hook. */
add_action( 'save_post', 'smashing_flautist_access_save_meta', 10, 2 );
}
/* Create one or more meta boxes to be displayed on the post editor screen. */
function smashing_add_post_meta_boxes() {
add_meta_box(
'smashing-flautist-access', // Unique ID
esc_html__( 'Post Viewing Permission', 'smashing_flautist' ), // Title
'smashing_flautist_access_meta_box', // Callback function
'destinations', // Admin page (or post type)
'normal', // Context
'default' // Priority
);
}
/* Display the post meta box. */
function smashing_flautist_access_meta_box( $object, $box ) { ?>
<?php wp_nonce_field( basename( __FILE__ ), 'smashing_flautist_access_nonce' ); ?>
<table class="smashing-flautist-access">
<tr align="left">
<th>Username</th>
<th> </th>
<th>Visiblity</th>
<th> </th>
<th>Name</th>
</tr>
<?php
global $post;
$users = get_users('role=subscriber');
foreach ($users as $user) {
$user_info = get_userdata( $user->ID );
if(get_post_meta( $object->ID, 'smashing_flautist_access', true ) == $user->user_login) $ifchecked = 'checked="checked" ';
echo "<tr>";
echo "<td>$user->user_login</td><td> </td>";
echo "<td align=\"center\"><input type=\"checkbox\" name=\"smashing-flautist-access\" id=\"smashing-flautist-access\" value=\"$user->user_login\" " . $ifchecked ."/></td><td> </td>";
echo "<td>$user_info->last_name, $user_info->first_name</td><td> </td>";
echo "</tr>";
unset($ifchecked);
} ?></table>
<?php }
/* Save post meta on the 'save_post' hook. */
add_action( 'save_post', 'smashing_flautist_access_save_meta', 10, 2 );
/* Save the meta box's post metadata. */
function smashing_flautist_access_save_meta( $post_id, $post ) {
/* Make all $wpdb references within this function refer to this variable */
global $wpdb;
/* Verify the nonce before proceeding. */
if ( !isset( $_POST['smashing_flautist_access_nonce'] ) || !wp_verify_nonce( $_POST['smashing_flautist_access_nonce'], basename( __FILE__ ) ) )
return $post_id;
/* Get the post type object. */
$post_type = get_post_type_object( $post->post_type );
/* Check if the current user has permission to edit the post. */
if ( !current_user_can( $post_type->cap->edit_post, $post_id ) )
return $post_id;
/* Get the posted data and sanitize it for use as an HTML class. */
$new_meta_value = ( isset( $_POST['smashing-flautist-access'] ) ? sanitize_html_class( $_POST['smashing-flautist-access'] ) : '' );
/* Get the meta key. */
$meta_key = 'smashing_flautist_access';
/* Get the meta value of the custom field key. */
$meta_value = get_post_meta( $post_id, $meta_key, true );
/* If a new meta value was added and there was no previous value, add it. */
if ( $new_meta_value && '' == $meta_value )
{
add_post_meta( $post_id, $meta_key, $new_meta_value, true );
$wpdb->query($wpdb->prepare("UPDATE $wpdb->posts SET post_status = 'private' WHERE ID = ".$post_id." AND post_type ='post'"));
}
/* If the new meta value does not match the old value, update it. */
elseif ( $new_meta_value && $new_meta_value != $meta_value )
{
update_post_meta( $post_id, $meta_key, $new_meta_value );
$wpdb->query($wpdb->prepare("UPDATE $wpdb->posts SET post_status = 'private' WHERE ID = ".$post_id." AND post_type ='post'"));
}
/* If there is no new meta value but an old value exists, delete it. */
elseif ( '' == $new_meta_value && $meta_value )
{
delete_post_meta( $post_id, $meta_key, $meta_value );
$wpdb->query($wpdb->prepare("UPDATE $wpdb->posts SET post_status = 'public' WHERE ID = ".$post_id." AND post_type ='post'"));
}
}
Instead of:
if(get_post_meta( $object->ID, 'smashing_flautist_access', true ) == $user->user_login) $ifchecked = 'checked="checked" ';
Try:
$ifchecked = (get_post_meta( $object->ID, 'smashing_flautist_access', true ) == $user->user_login)? 'CHECKED ':'';
Using this, you can also remove the unset($ifchecked); as you are always assigning $ifchecked a new value in each iteration. The unset doesn't hurt anything, it's just not necessary.
HTH,
=C=

How to set radio buttons in custom meta box checked?

I created a custom meta box where you can choose a value from some radio buttons and save it to the post_meta table in the wordpress database. With the following code I save the value:
function save_value_of_my_custom_metabox ($post_id, $post){
$post_id = get_the_ID();
$new_meta_value = ( isset( $_POST['the_name_of_the_radio_buttons'] ) ? sanitize_html_class( $_POST['the_name_of_the_radio_buttons'] ) : '' );
$meta_key = 'my_key';
update_post_meta( $post_id, $meta_key, $new_meta_value );
}
But if the post will be edited again I want the radio button with the current value to set checked. What is the best way to do that? Here is the function to display the meta box:
function my_custom_meta_box( $object, $box ) {
$post_id=get_the_ID();
$key='my_key';
$the_value_that_should_be_set_to_checked=get_post_meta( $post_id, $key);
//$the_value_that_should_be_set_to_checked[0] returns the value as string
?>
<label for="my_custom_metabox"><?php _e( "Choose value:", 'choose_value' ); ?></label>
<br />
<input type="radio" name="the_name_of_the_radio_buttons" value="value1">Value1<br>
<input type="radio" name="the_name_of_the_radio_buttons" value="value2">Value2<br>
<input type="radio" name="the_name_of_the_radio_buttons" value="value3">Value3<br>
<input type="radio" name="the_name_of_the_radio_buttons" value="value4">Value4<br>
<?php
}
I could write something like if(isset($the_value_that_should_be_set_to_checked[0])=="value of that line") echo "checked='checked'"; in every line but that doesn't seem very elegant to me. Using javascript is also pretty complicated in wordpress because I would have to use the hooks, enqueue the script and just for changing the checked property with one line of javascript it's not worth it. What's the best practice for that?
I am assuming that you are trying to add custom meta box for 'Posts'. Below code will work for you. It will show Radio buttons on add new post or edit post screen. Please read the comments in the code. It will help you in understanding the code.
You can use WordPress's checked function to decide whether to select the radio button or not.
Feel free to ask if you have any doubts.
/**
* Adds a box to the main column on the Post add/edit screens.
*/
function wdm_add_meta_box() {
add_meta_box(
'wdm_sectionid', 'Radio Buttons Meta Box', 'wdm_meta_box_callback', 'post'
); //you can change the 4th paramter i.e. post to custom post type name, if you want it for something else
}
add_action( 'add_meta_boxes', 'wdm_add_meta_box' );
/**
* Prints the box content.
*
* #param WP_Post $post The object for the current post/page.
*/
function wdm_meta_box_callback( $post ) {
// Add an nonce field so we can check for it later.
wp_nonce_field( 'wdm_meta_box', 'wdm_meta_box_nonce' );
/*
* Use get_post_meta() to retrieve an existing value
* from the database and use the value for the form.
*/
$value = get_post_meta( $post->ID, 'my_key', true ); //my_key is a meta_key. Change it to whatever you want
?>
<label for="wdm_new_field"><?php _e( "Choose value:", 'choose_value' ); ?></label>
<br />
<input type="radio" name="the_name_of_the_radio_buttons" value="value1" <?php checked( $value, 'value1' ); ?> >Value1<br>
<input type="radio" name="the_name_of_the_radio_buttons" value="value2" <?php checked( $value, 'value2' ); ?> >Value2<br>
<input type="radio" name="the_name_of_the_radio_buttons" value="value3" <?php checked( $value, 'value3' ); ?> >Value3<br>
<input type="radio" name="the_name_of_the_radio_buttons" value="value4" <?php checked( $value, 'value4' ); ?> >Value4<br>
<?php
}
/**
* When the post is saved, saves our custom data.
*
* #param int $post_id The ID of the post being saved.
*/
function wdm_save_meta_box_data( $post_id ) {
/*
* We need to verify this came from our screen and with proper authorization,
* because the save_post action can be triggered at other times.
*/
// Check if our nonce is set.
if ( !isset( $_POST['wdm_meta_box_nonce'] ) ) {
return;
}
// Verify that the nonce is valid.
if ( !wp_verify_nonce( $_POST['wdm_meta_box_nonce'], 'wdm_meta_box' ) ) {
return;
}
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
// Check the user's permissions.
if ( !current_user_can( 'edit_post', $post_id ) ) {
return;
}
// Sanitize user input.
$new_meta_value = ( isset( $_POST['the_name_of_the_radio_buttons'] ) ? sanitize_html_class( $_POST['the_name_of_the_radio_buttons'] ) : '' );
// Update the meta field in the database.
update_post_meta( $post_id, 'my_key', $new_meta_value );
}
add_action( 'save_post', 'wdm_save_meta_box_data' );
I found a working solution but I think this is not how you should do it. Still open for better solutions ;)
This code was added under the php code from above:
if(isset($$the_value_that_should_be_set_to_checked[0])){
$the_value_that_should_be_set_to_checked= $the_value_that_should_be_set_to_checked[0];
}
else{
$the_value_that_should_be_set_to_checked='';
}
Here's the code that I added below the radiobuttons:
<script type="text/javascript">
jQuery(document).ready(function () {
var checked_value= <?php echo json_encode($the_value_that_should_be_set_to_checked);?>;
if(checked_value!==''){
jQuery("input[name=the_name_of_the_radio_buttons][value="+checked_value+"]").attr('checked', 'checked');
}
});
</script>
P.S.: The $ selector will not work but that maybe depends on the theme you use.

Trying to add a custom meta box to wordpress

I am trying to add a custom meta box to a wordpress page which stores a value in a custom field. It is not working. The meta box is displayed but when you press update the value entered ito the text box is lost and nothing is written to the wp_postmeta table (no _c3m_sponsor_ur meta_key is created)
I have adapted this from an example online. I also tried adding a die statement to see if the save post is even called but nothing dies. I also dont understand why the add_post_meta isn't being created for the page
add_action( 'add_meta_boxes', 'c3m_sponsor_meta' );
function c3m_sponsor_meta() {
add_meta_box( 'c3m_meta', 'Sponsor URL Metabox', 'c3m_sponsor_url_meta', 'page', 'side', 'high' );
}
function c3m_sponsor_url_meta( $post ) {
$c3m_sponsor_url = get_post_meta( $post->ID, '_c3m_sponsor_url', true);
if (!isset($c3m_sponsor_url))
add_post_meta($post->ID, '_c3m_sponsor_url', '', false);
echo 'Please enter the sponsors website link below';
?>
<input type="text" name="c3m_sponsor_url" value="<?php echo esc_attr( $c3m_sponsor_url ); ?>" />
<?php
}
add_action( 'save_post', 'c3m_save_project_meta' );
function c3m_save_project_meta( $post_ID ) {
die('here');
global $post;
if( $post->post_type == "page" ) {
if (isset( $_POST ) ) {
update_post_meta( $post_ID, '_c3m_sponsor_url', strip_tags( $_POST['c3m_sponsor_url'] ) );
}
}
}
Any help in fixing this is muh appreciated
Thanks a lot
This may be help you:--
add_action( 'save_post', 'c3m_save_project_meta' );
function c3m_save_project_meta( $post_ID ) {
if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] )
{
if (isset( $_POST ) ) {
update_post_meta( $post_ID, '_c3m_sponsor_url', strip_tags( $_POST['c3m_sponsor_url'] ) );
}
}
}
Edited:-
You can simply use Advanced Custom Fields plugin instead of using code. This plugin much helpful for custom meta fields.

how to add a meta box to wordpress pages

i want to make this code for pages
add_action( 'add_meta_boxes', 'meta_box_video' );
function meta_box_video()
{
add_meta_box( 'video-meta-box-id', 'Video Embed', 'meta_box_callback', 'post', 'normal', 'high' );
}
function meta_box_callback( $post )
{
$values = get_post_custom( $post->ID );
$selected = isset( $values['meta_box_video_embed'] ) ? $values['meta_box_video_embed'][0] : '';
wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );
?>
<p>
<label for="meta_box_video_embed"><p>Video Embed</p></label>
<textarea name="meta_box_video_embed" id="meta_box_video_embed" cols="62" rows="5" ><?php echo $selected; ?></textarea>
</p>
<p>Leave it Empty ( if you want to use an image thumbnail ) .</p>
<?php
}
add_action( 'save_post', 'meta_box_video_save' );
function meta_box_video_save( $post_id )
{
// Bail if we're doing an auto save
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
// if our nonce isn't there, or we can't verify it, bail
if( !isset( $_POST['meta_box_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'my_meta_box_nonce' ) ) return;
// if our current user can't edit this post, bail
if( !current_user_can( 'edit_post' ) ) return;
// now we can actually save the data
$allowed = array(
'a' => array( // on allow a tags
'href' => array() // and those anchords can only have href attribute
)
);
// Probably a good idea to make sure your data is set
if( isset( $_POST['meta_box_video_embed'] ) )
update_post_meta( $post_id, 'meta_box_video_embed', $_POST['meta_box_video_embed'] );
}
This:
function meta_box_video()
{
add_meta_box( 'video-meta-box-id', 'Video Embed', 'meta_box_callback', 'post', 'normal', 'high' );
}
Should specify page not post.
function meta_box_video()
{ // --- Parameters: ---
add_meta_box( 'video-meta-box-id', // ID attribute of metabox
'Video Embed', // Title of metabox visible to user
'meta_box_callback', // Function that prints box in wp-admin
'page', // Show box for posts, pages, custom, etc.
'normal', // Where on the page to show the box
'high' ); // Priority of box in display order
}
Take a look at the Codex for add_meta_box(). The examples are very helpful. The portion you are interested in is under "Parameter". The fourth parameter allows you to specify whether you want the metabox on pages, posts, etc.

Resources