I created a couple meta fields in Wordpress for a Custom Post Type. They are 'Price' and 'Details'. If I got to the 'edit post' page, and i change something in one of these fields, but then decide to just leave the page by hitting 'back' in the browser or closing the window, i get a warning from my browser "are you sure you want to leave the page?". When I hit 'Yes', it erases anything that's in those 2 fields, even what was previously stored before my editing.
Any idea why this could be?
Here's some of my code in functions.php:
add_action("admin_init", "admin_init");
function admin_init()
{
add_meta_box("price", "Price", "price_field", "product", "normal", "high");
add_meta_box("details", "Details", "details_field", "product", "normal", "high");
}
function price_field()
{
global $post;
$custom = get_post_custom($post->ID);
$price = $custom["price"][0];
?>
<label>Price: $</label>
<input name="price" value="<?php echo $price; ?>" />
<?php
}
function details_field()
{
global $post;
$custom = get_post_custom($post->ID);
$details = $custom["details"][0];
?>
<label>Details:</label>
<input name="details" rows='5' value="<?php echo $details; ?>" />
<?php
}
/*--------------------------------*/
/* Save PRICE and DETAILS fields */
/*--------------------------------*/
add_action('save_post', 'save_details');
function save_details()
{
global $post;
update_post_meta($post->ID, "price", $_POST["price"]);
update_post_meta($post->ID, "details", $_POST["details"]);
}
This is because you didnt add filtering in your save details method. Remember action hook "save_post" is also called once the post is auto save in draft even if you didnt click the update or the publish button. Try this
add_action('save_post', 'save_details');
function save_details($post_id){
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
// uncomment if youre using nonce
//if ( !wp_verify_nonce( $_POST['my_noncename'], plugin_basename( __FILE__ ) ) )
// return;
// Check permissions
//change the "post" with your custom post type
if ( 'post' == $_POST['post_type'] )
{
if ( !current_user_can( 'edit_page', $post_id ) )
return;
}
else
{
if ( !current_user_can( 'edit_post', $post_id ) )
return;
}
//if success go to your process
//you can erase your global $post and dont use $post->ID rather change it with $post_id since its our parameter
update_post_meta($post_id, "price", $_POST["price"]);
update_post_meta($post_id, "details", $_POST["details"]);
}
NOTE: in if ( 'post' == $_POST['post_type'] ) line, change "post" to your post type
Related
I'm Trying to make a plugin that send emails with the post content to an email when admin
check the check box. I found some codes and trying to do this
The plugin creates meta box with check box custom field.
Problem:
Not able to get custom field value in the plugin using get_post_meta to check whether to send the email or not
Following is the code:
add_action('admin_init','add_metabox_post_sidebar');
add_action('save_post','save_metabox_post_sidebar');
/*
* Funtion to add a meta box to enable/disable the posts.
*/
function add_metabox_post_sidebar()
{
add_meta_box("Enable Sidebar", "Enable Sidebar", "enable_sidebar_posts", "post", "side", "high");
}
function enable_sidebar_posts(){
global $post;
$check=get_post_custom($post->ID );
$checked_value = isset( $check['post_sidebar'] ) ? esc_attr( $check['post_sidebar'][0] ) :
'no';
?>
<label for="post_sidebar">Enable Sidebar:</label>
<input type="checkbox" name="post_sidebar" id="post_sidebar" <?php if($checked_value=="yes")
{echo "checked=checked"; } ?> >
<?php
}
/*
* Save the Enable/Disable sidebar meta box value
*/
function save_metabox_post_sidebar($post_id)
{
// Bail if we're doing an auto save
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
// if our current user can't edit this post, bail
if( !current_user_can( 'edit_post' ) ) return;
$checked_value = isset( $_POST['post_sidebar'] ) ? 'yes' : 'no';
update_post_meta( $post_id, 'post_sidebar', $checked_value );
}
// Function that runs when a post is published
function run_when_post_published( $post ) {
$author = get_userdata($post->post_author);
$category = get_the_category();
$author_id = $post->post_author;
$author = get_the_author_meta( 'nickname', $author_id );
$title = get_the_title();
$permalink = get_permalink();
$featured = get_the_post_thumbnail_url();
$email_subject = $title;
$message = apply_filters( 'the_content', $post->post_content );
$message2=wp_strip_all_tags($message);
$message3= html_entity_decode($message2);
$headers = 'Manarty <info#example.com>';
global $wp_query;
$thePostID = $wp_query->post->ID;
$k=get_post_meta( $thePostID, 'post_sidebar', true);
if(!empty($k) ) {
$email = 'test#test.com';
wp_mail( $email, $email_subject, $message3 );
}
}
// Makes sure email only gets sent the first time a post is published
add_action('new_to_publish', 'run_when_post_published');
add_action('draft_to_publish', 'run_when_post_published');
add_action('pending_to_publish', 'run_when_post_published');
It think your problem might be here:
$k=get_post_meta( $thePostID, 'post_sidebar', true);
if in fact you already had saved 'post_sidebar' correctly it means that you don't have the correct value of $thePostID
Instead of your code try this, it works for me:
global $post;
$currentPostObject = $post;
$currentPostObjectID = $currentPostObject->ID;
I have a metabox (one checkbox) , in posts, to check if a post will be featured..
My code:
function add_featured_post_checkbox() {
add_meta_box(
'custom_featured_meta',
'Featured post for Sidebar',
'featured_post_checkbox_callback',
'Post',
'side',
'high'
);
} add_action( 'add_meta_boxes', 'add_featured_post_checkbox' );
Callback function:
function featured_post_checkbox_callback( $post ) {
wp_nonce_field( 'custom_save_data' , 'custom_featured_nonce' );
$featured = get_post_meta($post->ID, '_featured_post', true);
echo "<label for='_featured_post'>".__('Is Featured? ', 'foobar')."</label>";
echo "<input type='checkbox' name='_featured_post' id='featured_post' value='1' " . checked(1, $featured) . " />";
}
Save function:
function custom_save_data( $post_id ) {
if( ! isset( $_POST['custom_featured_nonce'] ) ){
return;
}
if( ! wp_verify_nonce( $_POST['custom_featured_nonce'], 'custom_save_data') ) {
return;
}
if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){
return;
}
if( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
if( ! isset( $_POST['_featured_post'] ) ) {
return;
}
$my_data_featured = sanitize_text_field( $_POST['_featured_post'] );
update_post_meta( $post_id, '_featured_post', $my_data_featured );
} add_action( 'save_post', 'custom_save_data' );
This code works well only when I want to make a post featured..
For example if a post is not checked as featured and I select the choice then database updated perfect (with value 1 in post_meta) and the ckeckbox has the tick on box
But after, If I try to uncheck and save the post then the ckeckbox is again with the tick and nothing changed in database..
I try to find a solution for days on stackoverflow and general in web but I can't find.
Please help me
Thank you
When a checkbox is unchecked, $_POST will not contain the key _featured_post. Therefore, in your save callback, you need to change your strategy. You do not want to bail out if the key is not set. Rather, you either want to save a 0 or delete the post meta. Let's go with the later option.
function custom_save_data( $post_id ) {
if( ! isset( $_POST['custom_featured_nonce'] ) ){
return;
}
if( ! wp_verify_nonce( $_POST['custom_featured_nonce'], 'custom_save_data') ) {
return;
}
if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ){
return;
}
if( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
if ( isset( $_POST['_featured_post'] ) ) {
update_post_meta( $post_id, '_featured_post', 1 );
} else {
delete_post_meta( $post_id, '_featured_post' );
}
}
Notice that you do not need to use sanitize_text_field(). Why? Because the value will only be a 1. That's it. Here we can hardcode that value.
Another Problem I Saw
Running your code I saw that upon being checked, the HTML for checked=checked is being rendered as text. Why? Because running the function checked() will echo it out to the browser unless you tell it not to. You'd have to check your code to:
checked(1, $featured, false);
That's happening because of return after the check if _featured_post is set in $_POST array. It's not set when you do not check the checkbox. Your approach here should be next
if (isset($_POST['_featured_post']))
{
update_post_meta($object_id, '_featured_post', 1); // can only be 1 when checked anyway
}
else
{
delete_post_meta($object_id, '_featured_post');
}
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);
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.
I want to save the data of my custom meta box to the corresponding table in a field.
my custom metabox..
add_action( 'admin_init', 'blc_add_custom_link_box', 1 );
add_action( 'save_post', 'blc_save_linkdata' );
function blc_add_custom_link_box() {
add_meta_box(
'backlinkdiv',
'Backlink URL',
'blc_backlink_url_input',
'link',
'normal',
'high'
);
}
function blc_backlink_url_input( $post ) {
// Use nonce for verification
wp_nonce_field( plugin_basename( __FILE__ ), 'blc_noncename' );
// The actual fields for data entry
echo '<input type="text" id="backlink-url" name="backlink_url" value="put your backlink here" size="60" />';
function blc_save_linkdata( $link_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
if ( !wp_verify_nonce( $_POST['blc_noncename'], plugin_basename( __FILE__ ) ) )
return;
if ( 'link' == $_POST['link_type'] )
{
if ( ! current_user_can( 'edit_page', $link_id ) )
return;
}
else
{
if ( !current_user_can( 'edit_post', $link_id ) )
return;
}
$blc_linkdata = $_POST['blc_link'];
?>
now i want to store the data in to the database table WP_link in a custom field. i got meta box in the link edit admin page . but it cant save the data in database. how it can be save in database table wp_link.
I want know how to save the $blc_linkdata from custom metafield from the link edit page.
Plz help..
You should find this page on the Wordpress Codex useful: http://codex.wordpress.org/Function_Reference/add_post_meta
I would simply use the Meta Box Script from DeluxeBlogTips.
I'm also working on a (huge) site that requires (many) metabox/custom field integrations. Trust me, this will save you lots of time and is well written and thoroughly tested ;)