I added a meta-box to the edit link page & I can't save the data whatever I put in the field. How can I only update the meta-box without saving the data in the database? Here is my code:
// backwards compatible
add_action( 'admin_init', 'blc_add_custom_link_box', 1 );
/* Do something with the data entered */
add_action( 'save_link', 'blc_save_linkdata' );
/* Adds a box to the main column on the Post and Page edit screens */
function blc_add_custom_link_box() {
add_meta_box(
'backlinkdiv',
'Backlink URL',
'blc_backlink_url_input',
'link',
'normal',
'high'
);
}
/* Prints the box content */
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" />';
#echo "<p> _e('Example: <code>http://Example.org/Linkpage</code> — don’t forget the <code>http://</code>')</p>";
}
How can I save or update the data of the input field of metabox? Only the data should be updated in the metabox. It should not save in database by any type of custom field.
I think it actually would be a good idea to save as a custom field, only one that doesn't show up in the custom field box. You can accomplish the latter by adding a "_" at the beginning of the custom field's name (i.e. "_my_custom_field" instead of "my_custom_field".
Here's a sample function to save your meta box data. I changed the names to match the code you have above.
:
<?php
function blc_save_postdata($post_id){
// 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['blc_noncename'], plugin_basename(__FILE__) )) {
return $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 )
return $post_id;
// Check permissions to edit pages and/or posts
if ( 'page' == $_POST['post_type'] || 'post' == $_POST['post_type']) {
if ( !current_user_can( 'edit_page', $post_id ) || !current_user_can( 'edit_post', $post_id ))
return $post_id;
}
// OK, we're authenticated: we need to find and save the data
$blc = $_POST['backlink_url'];
// save data in INVISIBLE custom field (note the "_" prefixing the custom fields' name
update_post_meta($post_id, '_backlink_url', $blc);
}
//On post save, save plugin's data
add_action('save_post', array($this, 'blc_save_postdata'));
?>
And that should be it. I used this page as a reference: http://codex.wordpress.org/Function_Reference/add_meta_box
Hook the action save_post - it receives saved post ID and allows you to update the post the way you need when submitting post editor page. Don't forget that this action will be called for EVERY post saved - you need to only handle posts having your custom meta box.
you must disable this code
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return $post_id;
what it does is that it blocks your code below cause it detects that your doing some auto save on it.
Related
on my baked goods site, I have WooCommerce installed and another plugin called Order Delivery Date for WooCommerce.
I installed the second plugin so my customers would be able to choose a delivery date for their items, however, I am trying to make the form field a required field. So far, I've just been able to make the field look like a required field, but have not figured out how to make sure that it is actually enforced. Any ideas?
Also, if anyone is familiar with WooCommerce, do you know how I would be able to make it so that customers receive this delivery date information in their order confirmation emails?
Thank you in advance!
My site: www.monpetitfour.com
You should try to had something like that :
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
function my_custom_checkout_field_process() {
// You can make your own control here
if ( ! $_POST[ 'e_deliverydate' ] )
wc_add_notice( __( 'Please select a delivery date' ), 'error' );
}
For the email, the easiest is to save the meta value ( I think it's already done by your plugin). Then you need to copy the template email (customer-processing-order.php) on your theme and change in the template :
<?php $delivery_date = get_post_meta( $order->id, 'custom_field_date', true);
// If the plugin is well developed, you can't directly use magic getters :
// $delivery_date = $order->e_deliverydate;
// Can only by use if the post meta start with _
?>
Your delivery date is <?php echo $delivery_date ?>
You can also use
date_i18n( woocommerce_date_format(), strtotime( $delivery_date ) );
In order to format the date correctly.
On the code above, you just need to find the name of the custom field used by the plugin ( you can search easily on the table wp_postmeta searching by an existing order (should be _e_deliverydate).
Add the following code to your theme's functions.php file
add_action('woocommerce_checkout_process', 'my_custom_checkout_field_process');
function my_custom_checkout_field_process() {
// Check if set, if its not set add an error.
if ( ! $_POST['e_deliverydate'] )
wc_add_notice( __( 'Please select a delivery date.' ), 'error' );
}
Now to get the email to show the custom field,
add_filter('woocommerce_email_order_meta_keys', 'my_woocommerce_email_order_meta_keys');
function my_woocommerce_email_order_meta_keys( $keys ) {
$keys['Delivery Date'] = '_e_deliverydate';
return $keys;
}
EDIT : Seems the field value isn't being saved to the database, try saving it explicitly
add_action( 'woocommerce_checkout_update_order_meta', 'my_custom_checkout_field_update_order_meta' );
function my_custom_checkout_field_update_order_meta( $order_id ) {
if ( ! empty( $_POST['e_deliverydate'] ) ) {
update_post_meta( $order_id, '_e_deliverydate', sanitize_text_field( $_POST['e_deliverydate'] ) );
}
}
I've created a meta box. The code is:
// Create your custom meta box
add_action( 'add_meta_boxes', 'hotel_amenities' );
// Add a custom meta box to a post
function hotel_amenities( $post ) {
add_meta_box(
'Meta Box Amenities', // ID, should be a string
'Amenities', // Meta Box Title
'amenities_content', // Your call back function, this is where your form field will go
'post', // The post type you want this to show up on, can be post, page, or custom post type
'normal', // The placement of your meta box, can be normal or side
'high' // The priority in which this will be displayed
);
}
// Content for the custom meta box
function amenities_content( $post ) {
echo '<label>Bed room</label>';
echo '<input type="text" name="amenity_bed_room" value="" />';
}
// Save your meta box content
add_action( 'save_post', 'save_amenities' );
// save newsletter content
function save_amenities(){
global $post;
// Get our form field
if( $_POST ) :
$amenities_meta = esc_attr( $_POST['amenity_bed_room'] );
// Update post meta
update_post_meta($post->ID, '_amenities_custom_meta', $amenities_meta);
endif;
}
It shows a meta box on admin post page with a text field. but it gets blank if I save or update the post after I put some thing on the text field.
Seems function save_amenities() is not working. What I am doing wrong in this code?
Also for getting that value I use the function below. Is that correct?
//get amenities meta box values
function get_amenities_meta_box() {
global $post;
$meta_values = get_post_meta($post->ID, '_amenities_custom_meta', true);
}
There are a few things going wrong there. The final value that you want to see will be displayed by the value attribute in the amenities_content function. Right now it is just displaying an empty string (""). Try putting any value in that attribute and you should see it show up in the meta box (value="this is a test").
The save_amenities function should take $post_id as a parameter. You'll need that to update the post meta-data and give a real value for the amenities_content function to echo back to the admin screen.
The amenities_content function should really have a nonce field that should then be verified by the save_amenities function. And user input should be sanitized before it is saved (I'm doing it both when I save it and when I display it. I'm not sure if that's necessary.)
try this out for the amenities_content function:
function amenities_content( $post ) {
// This is the value that was saved in the save_amenities function
$bed_room = get_post_meta( $post->ID, '_amenity_bed_room', true );
wp_nonce_field( 'save_amenity', 'amenity_nonce' );
echo '<label>Bed room</label>';
echo '<input type="text" name="amenity_bed_room"
value="' . sanitize_text_field( $bed_room ) . '" />';
}
and this for the save_amenities function:
function save_amenities( $post_id ) {
// Check if nonce is set
if ( ! isset( $_POST['amenity_nonce'] ) ) {
return $post_id;
}
if ( ! wp_verify_nonce( $_POST['amenity_nonce'], 'save_amenity' ) ) {
return $post_id;
}
// Check that the logged in user has permission to edit this post
if ( ! current_user_can( 'edit_post' ) ) {
return $post_id;
}
$bed_room = sanitize_text_field( $_POST['amenity_bed_room'] );
update_post_meta( $post_id, '_amenity_bed_room', $bed_room );
}
How to update custom post custom field value when post is saved in admin?
I have tried to use this in misc.php for admin section:
add_action('pre_post_update', 'do_something_with_a_post');
function do_something_with_a_post($id) {
global $post;
update_post_meta($id, 'ct_Course_Dur_text_d19c', 'test12');
)
But it is not working.
You may try this (Using save_post hook), paste this code in your functions.php file
function save_cpt_metadata($id, $post)
{
if($post->post_type != 'your_custom_post_type') {
return;
}
update_post_meta($id, 'ct_Course_Dur_text_d19c', sanitize_text_field( $_POST['your_custom_field'] ) );
}
add_action('save_post', 'save_cpt_metadata');
In this example sanitize_text_field( $_POST['your_custom_field'] ) is would be actually the cstom field on your form but you may use any hard coded data, replace the your_custom_post_type with your real custom post type.
I wanted to create a plugin to batch manage posts' custom field data. I know I can add post meta by adding a meta box in the post edit screen and using add_action('save_post', 'function_to_update_meta') to trigger add meta functions.
But I don't know how to trigger the add_post_meta function in an admin menu page (such as a custom admin menu). How to do that?
Thank you in advance!
The example given in Wordpress' codex is probably the best and most secure in the way of processing information:
Add Meta Box
Copy and paste it and then fiddle around with it to get a good idea on how to control your posts and pages.
The nice part is that you don't need to worry about checking if you need to Add vs Update a given Post Meta field. Using Update Post Meta will ensure that the proper action is taken for you, even if the field doesn't exist.
The same goes for Update Option if you want to add some global controls that your plugin/theme might use.
BREAKDOWN EXAMPLE:
add_action( 'add_meta_boxes', 'myplugin_add_custom_box' );
add_action( 'save_post', 'myplugin_save_postdata' );
These are the action hooks. The first one is executed when meta boxes are being populated within the post editor, and the second is executed when a post is added OR updated.
function myplugin_add_custom_box()
{
add_meta_box(
'myplugin_sectionid',
__( 'My Post Section Title', 'myplugin_textdomain' ),
'myplugin_inner_custom_box',
'post'
);
add_meta_box(
'myplugin_sectionid',
__( 'My Post Section Title', 'myplugin_textdomain' ),
'myplugin_inner_custom_box',
'page'
);
}
This function is called by the 'add_meta_boxes' action hook. Notice the name of the function and the second argument of the action hook are exactly the same. This registers your meta boxes, which post types they're supposed to appear, and what callback is used to generate the form contained inside.
function myplugin_inner_custom_box( $post )
{
wp_nonce_field( plugin_basename( __FILE__ ), 'myplugin_noncename' );
$value = get_post_meta($post->ID, 'myplugin_new_field') ? get_post_meta($post->ID, 'myplugin_new_field') : 'New Field';
echo '<label for="myplugin_new_field">';
_e("Description for this field", 'myplugin_textdomain' );
echo '</label> ';
echo '<input type="text" id="myplugin_new_field" name="myplugin_new_field" value="'.$value.'" size="25" />';
}
This is the function that is called by the registered meta boxes to generate the form automatically. Notice how the function is called 'myplugin_inner_custom_box' and the 3rd argument in your meta box registration is also called 'myplugin_inner_custom_box'.
The wp_nonce_field() generates a hidden field in your form to verify that data being sent to the form actually came from Wordpress, and can also be used to end the function in case other plugins are using the 'save_post' action hook.
Notice also that the $post object is being passed in as an argument. This will allow you to use certain properties from the post object. I've taken the liberty of checking to see if there is get_post_meta() returns anything with the given post ID. If so, the field is filled with that value. If not, it is filled with 'New Field'.
function myplugin_save_postdata( $post_id )
{
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
if ( !wp_verify_nonce( $_POST['myplugin_noncename'], plugin_basename( __FILE__ ) ) )
return;
if ( 'page' == $_POST['post_type'] )
{
if ( !current_user_can( 'edit_page', $post_id ) )
return;
}
else
{
if ( !current_user_can( 'edit_post', $post_id ) )
return;
}
$mydata = $_POST['myplugin_new_field'];
update_post_meta($post_id, 'myplugin_new_field', $mydata);
}
This is the function that is called by the 'save_post' action hook. Notice how the second argument of the second action hook and this function are both called 'myplugin_save_postdata'. First, there are a series of verifications our plugin must pass before it can actually save any data.
First, we don't want our meta boxes to update every time the given post is auto-updating. If the post is auto-updating, cancel the process.
Secondly, we want to make sure the nonce data is available and verify it. If no nonce data is available or is not verified, cancel the process.
Thirdly, we want to make sure the given user has the edit_page permission. The function first checks the post type, and then checks the appropriate permission. If the user does not have that permission, cancel the process.
Lastly, our plugin has finally been verified and we want to save the information. I took the liberty of adding in the final update_post_meta() line to show you how it all comes together.
Notice how $post_id was passed into the function as an argument. This is one of the pieces needed for the update_post_meta() function. The key was named 'myplugin_new_field' and the value of that metadata is now saved as whatever you input into that custom input field in your custom meta box.
That's about as easy as I can explain the whole process. Just study it, and get your hands dirty with code. The best way to learn is through application rather than theory.
The answer was from the same question I asked somewhere else
And I created my version of example
I added some console.log function for testing, but this is basically doning the same thing as #Chris_() answer:
Menu callback function to generate menu content (PHP):
function ajax_menu_callback() {
?>
<div class="wrap">
<div id="icon-themes" class="icon32"></div>
<h2>Test</h2>
<br />
<form>
<input id="meta" type ="text" name="1" value="<?php echo esc_html( get_post_meta( 1, 'your_key', true) ); ?>" />
<?php submit_button(); ?>
</form>
</div>
<?php
}
Then the javascript to print on the admin side (javascript, don't forget to include a jquery library):
jQuery(document).ready(function() {
$("form").submit(function() {
console.log('Submit Function');
var postMeta = $('input[name="1"]').val();
console.log(postMeta);
var postID = 1;
var button = $('input[type="submit"]');
button.val('saving......');
$.ajax({
data: {action: "update_meta", post_id: postID, post_meta: postMeta, },
type: 'POST',
url: ajaxurl,
success: function( response ) { console.log('Well Done and got this from sever: ' + response); }
}); // end of ajax()
return false;
}); // end of document.ready
}); // end of form.submit
Then the PHP function handle update_post_meta (PHP):
add_action( 'wp_ajax_update_meta', 'my_ajax_callback' );
function my_ajax_callback() {
$post_id = $_POST['post_id'];
$post_meta = $_POST['post_meta'];
update_post_meta( $post_id, 'your_key', $post_meta );
echo 'Meta Updated';
die();
} // end of my_ajax_callback()
it's been almost 2 hours that I have been browsing here at stackoverflow for answers. I have managed to make my uploading of files function well by reading some answers here. But this time can't be helped. I really need to ask on how to save the path of the uploaded file after uploading. See, I use uploadify in my wordpress plugin. What I did was save the uploaded files(.pdf to be exact) to a specific folder on my directory.Then what I want is to save the path of the saved file when the post is being published. So technically,after the upload, I want to have the path of the uploaded file somewhere in the post such that when I publish the post, the path will also be saved in the database. Is this even possible?
This is my code snippet in my plugin,
/* Displays the box content which is the dropdown list of Funds */
function wnm_pengana_investor_upload_investor_box( $post ) {
/* Use nonce for verification */
wp_nonce_field( plugin_basename( __FILE__ ), 'wnm_pengana_funds_noncename' );
echo '<p class="uploadify_container">';
echo '<label style="margin-left: 15px;" for="investor_file_upload">Upload one or more files at once.</label>';
echo '<input type="file" name="investor_file_upload" id="investor_file_upload" />';
echo '</p>';
}
/* When the post is saved, saves our custom data */
function wnm_pengana_save_investor_upload_box( $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 )
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( isset($_POST['wnm_pengana_funds_noncename']), plugin_basename( __FILE__ ) ) )
return;
// Check permissions
if ( 'page' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_page', $post_id ) )
return;
} else {
if ( !current_user_can( 'edit_post', $post_id ) )
return;
}
// OK, we're authenticated: we need to find and save the data
$mydata = $_POST['investor_file_upload'];
update_post_meta($post_id, 'uploaded_forms_path', $mydata);
}
Currently, when published, the postmeta uploaded_forms_path will be added on the postmeta table, however it is empty. I think I need to put something after `echo '<input type="file" name="investor_file_upload" id="investor_file_upload" />';
sadly I don't know what am I to put. Can anyone help me? Thanks.`
Thank you everyone. It seems no one wanted to answer so I have to desperately find an answer for me.
Okay, what I did was , after saving the file, from the file uploadify.php, if the file upload is successful, I return the $newTargetFile such that using the onUploadSuccess event of uploadify, I can display the value of $newTargetFile which is the path of the uploaded file. I then assign this as a value of the hidden <input value="$newTargetFile" />, so when the post is being published , the data of that hidden input will be posted as postmeta data. :)