I have a custom metabox that I created and have been using on my website for a while, but there's a bit of an issue with how it saves. It tends to be rather volatile, meaning that when backing-up with xml or bulk-editing, it will always lose the data.
The following is the code that I use for the checkbox and to save it
function member_page_featured_meta() {
add_meta_box( 'member_page_meta', __( 'Page Template (if default, select none)', 'member_page_textdomain' ), 'member_page_meta_callback', 'page', 'side', 'low' );
}
add_action( 'add_meta_boxes', 'member_page_featured_meta' );
/**
* Outputs the content of the meta box
*/
function member_page_meta_callback( $post ) {
$values = get_post_meta( $post->ID );
$check = isset( $values['member_box_check'] ) ? esc_attr( $values['member_box_check'][0] ) : '';
wp_nonce_field( basename( __FILE__ ), 'member_page_nonce' );
$member_page_stored_meta = get_post_meta( $post->ID );
?>
<p>
<div class="member_page-row-content">
<label for="featured-checkbox">
<input type="checkbox" name="featured-checkbox" id="featured-checkbox" value="yes" <?php if ( isset ( $member_page_stored_meta['featured-checkbox'] ) ) checked( $member_page_stored_meta['featured-checkbox'][0], 'yes' ); ?> />
<?php _e( 'Member Page', 'member_page_textdomain' )?>
</label><br />
<label for="list-checkbox">
<input type="checkbox" name="list-checkbox" id="list-checkbox" value="yes" <?php if ( isset ( $member_page_stored_meta['list-checkbox'] ) ) checked( $member_page_stored_meta['list-checkbox'][0], 'yes' ); ?> />
<?php _e( 'Home List', 'member_page_textdomain' )?>
</label><br />
</div>
</p>
<?php
}
/**
* Saves the custom meta input
*/
function member_page_meta_save( $post_id ) {
// Checks save status - overcome autosave, etc.
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'member_page_nonce' ] ) && wp_verify_nonce( $_POST[ 'member_page_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';
// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
// Checks for input and saves - save checked as yes and unchecked at no
//This line of code is my hack (just keeps the boxes from saving pretty much)
//if (!empty($_POST['featured-checkbox']) && !empty($_POST['list-checkbox'])) {
if( isset( $_POST[ 'featured-checkbox' ] ) ) {
update_post_meta( $post_id, 'featured-checkbox', 'yes' );
} else {
update_post_meta( $post_id, 'featured-checkbox', 'no' );
};
if( isset( $_POST[ 'list-checkbox' ] ) ) {
update_post_meta( $post_id, 'list-checkbox', 'yes' );
} else {
update_post_meta( $post_id, 'list-checkbox', 'no' );
};
// (bracket ending the first if statement) }
}
add_action( 'save_post', 'member_page_meta_save' );
Is there any way to prevent this issue from happening or is it just something that has to be dealt with when saving check-boxes?
I've sorted out a bit of a hack that is working for now, but whenever I need to make changes to the check-boxes (which is fairly often by the nature of how they're used), I have to comment out a few lines of code, make the change, then un-comment the lines of code and it's a bit unconventional.
I mostly need to make it work when backing-up and restoring (on my backup/production website).
The save_post action is triggered when a post is created or updated, so quick edits and regular edits and the import of posts will trigger it too.
It is actually your script which clears the post meta when doing a quick edit or import, because the POST array does not contain the previously saved values of the checkboxes.
To solve this, you might want to know the "type of saving" currently happening, and only update the post meta when you are on the post edit screen in the admin area. A way of doing this is to check the action parameter of the POST array like the following, because the action parameter only has the value editpost when saving from a post edit screen:
if (filter_input(INPUT_POST, 'action') != 'editpost') {
return;
}
Putting this code at the beginning of the function hooked to the save_post action (member_page_meta_save in your case) will let the rest of the function run only when saving from the post edit screen.
Related
HI first of thanks and i love this community . I stuck in problem where i want to store the image/item ID in localhost wordpress database instead of image path. I tried everything but failed. Well i am newbie in wordpress so i need a help.
suppose my image/item id is like:---- http://localhost/wpmegameta/wp-admin/upload.php?item=45
databse path:----http://localhost/wpmegameta/wp-content/uploads/2019/05/coding.png
and i want to store only 45 in database
Wordpress database Screenshot
and I want to store only 45 in database like this ---
wp_nonce_field( 'case_study_bg_submit', 'case_study_bg_nonce' );
$lacuna2_stored_meta = get_post_meta( $post->ID ); ?>
<p>
<label for="case-study-bg" class="lacuna2-row-title">Practice Area Icon Image</label>
<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]; } ?>" />
<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', 'Game Image', 'lacuna2_case_study_bg', 'post', 'side', 'low' );
}
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' );
In wordpress
Image /Item ID==45
Image Path== http://localhost/wpmegameta/wp-content/uploads/2019/05/coding.png
i want to store the image/item ID in wordpress database like=45
i think it's stander to store the image URL ,
but if you want to store just the id do that is to create a table contain all images URL's
and contains tow columns : ID,URL
hope this useful .
I've created a Custom Post Type 'media-page-items' that I'm attempting to add meta boxes to. Currently the meta boxes are showing but not saving to the database. I've tried a few different approaches on it and none of them seem to save to database.
Debug is turned on but no errors are being thrown currently that I can see.
Any help is much appreciated!
//add article link to media page item
add_action( 'admin_menu', 'gruman_article_link_create' );
add_action( 'save_post', 'gruman_article_link_save', 10, 2 );
function gruman_article_link_create() {
add_meta_box( 'gruman-article-link', 'Article Link', 'gruman_article_link', 'media-page-items', 'advanced', 'high' );
}
function gruman_article_link( $post ) {
// retrieve the _gruman_article_title current value
$current_article_link = get_post_meta( $post->ID, '_gruman_article_link', true );
?>
<p>
<label>Article Link</label>
<br />
<input name="gruman-article-link" id="article-link" style="width: 97%;"><?php $current_article_link; ?>/>
<input type="hidden" name="gruman_article_link_nonce" value="<?php echo wp_create_nonce( plugin_basename( __FILE__ ) ); ?>" />
</p>
<?php }
function gruman_article_link_save( $post_id ) {
// verify taxonomies meta box nonce
if ( !isset( $_POST['gruman_article_link_nonce'] ) || !wp_verify_nonce( $_POST['gruman_article_link_nonce'], basename( __FILE__ ) ) ){
return $post_id;
}
// return if autosave
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ){
return $post_id;
}
// Check the user's permissions.
if ( !current_user_can( 'edit_post', $post_id ) ){
return $post_id;
}
// store article title value
if ( isset( $_REQUEST['gruman-article-link'] ) ) {
update_post_meta( $post_id, '_gruman_article_link', sanitize_text_field( $_POST['gruman-article-link'] ) );
}
}
In wp_create_nonce you are using plugin_basename( __FILE__ ).
And when you verifying nonce you use basename( __FILE__ ) as action name.
Those values are not the same. First one will return something like my-plugin/my-plugin.php and the second will be my-plugin.php
That is why I believe wp_verify_nonce returns False and your data is not saved.
I am trying to add some custom meta boxes to my wordpress post edit page. I have the box added (Video URL) but when I attempt to call the info from the post into the field as the set value nothing ever shows. I believe I am saving it correctly, but I can't get it to show after being saved, please help. Here is the code for adding and saving the meta box info:
<!-- adding the video url meta box prototype data -->
<?php
add_action( 'add_meta_boxes', 'cd_meta_box_add' );
function cd_meta_box_add()
{
add_meta_box( 'post-video', 'Video URL', 'video_url_meta_box', 'post', 'side', 'high' );
}
?>
<!-- rendering the video url meta box on the post edit page -->
<?php
function video_url_meta_box( $post )
{
$value = get_post_meta( $post->ID, 'video_url_text', true );
wp_nonce_field( 'video_url_nonce', 'meta_box_nonce' );
?>
<p>
<label for="video_url_text">Youtube or Vimeo URL</label>
<input type="text" name="video_url_text" id="video_url_text" value="<?php echo $value; ?>" />
</p>
<?php
}
?>
<!-- Saving the video url meta box data -->
<?php
add_action( 'save_post', 'video_url_save' );
function video_url_save( $post_id )
{
//return if we're doing an auto save
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
//return if we can't verify nonce or it isn't there
if( !isset( $_POST['video_url_nonce'] ) || !wp_verify_nonce( $_POST['meta_box_nonce'], 'video_url_nonce' ) ) return;
//return if the current user can't edit the post
if( !current_user_can( 'edit_page' ) ) return;
// save data once all checks are passed
// make sure the url is set
if( isset( $_POST['video_url_text'] ) )
update_post_meta( $post_id, 'video_url_text' );
}
?>
I ended up moving all of the code into a custom plugin and got it working as shown below:
/**
* Adds the meta boxes to the post editing screen
*/
function weshine_meta_boxes() {
add_meta_box( 'video_url_meta', __( 'Video URL', 'video-url-text' ), 'video_url_meta_callback', 'post', 'side', 'high' );
add_meta_box( 'caption_text_meta', __( 'Caption Text', 'thumb-caption-text' ), 'caption_text_meta_callback', 'post', 'side', 'high');
}
add_action( 'add_meta_boxes', 'weshine_meta_boxes' );
/**
* Outputs the content of the meta box
*/
function video_url_meta_callback( $post ) {
wp_nonce_field( basename( __FILE__ ), 'prfx_nonce' );
$video_url_stored_meta = get_post_meta( $post->ID );
?>
<p>
<label for="video-url" class="prfx-row-title"><?php _e( 'Enter Youtube or Vimeo URL', 'video-url-text' )?></label>
<input type="text" name="video-url" id="video-url" value="<?php if ( isset ( $video_url_stored_meta['video-url'] ) ) echo $video_url_stored_meta['video-url'][0]; ?>"$
</p>
<?php
}
/**
* Saves the custom meta input
*/
function video_url_meta_save( $post_id ) {
// Checks save status
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'prfx_nonce' ] ) && wp_verify_nonce( $_POST[ 'prfx_nonce' ], basename( __FILE__ ) ) ) ? '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[ 'video-url' ] ) ) {
update_post_meta( $post_id, 'video-url', sanitize_text_field( $_POST[ 'video-url' ] ) );
}
}
add_action( 'save_post', 'video_url_meta_save' );
I am creating a metabox that loops through all the posts of another CPT: 'product'. The metabox lists all the published products in that CPT, puts them in a table row along with an input box. Each input box has a unique ID based off of the CPT product id.
Most of this code I have added based on other posts, but I am having a problem saving the data. I know that it has to do with my value="", my nonce, and $meta_value, but I am not sure where to go next. Below is the code I have so far:
<?php
add_action('admin_init', 'my_theme_on_admin_init');
function my_theme_on_admin_init() {
add_meta_box('my_metabox',
__('Daily Inventory Levels', 'textdomain'),
'my_metabox_render',
'location_inventory', 'normal', 'high'
);
}
function my_metabox_render($post) {
// using an underscore, prevents the meta variable
// from showing up in the custom fields section
global $woocommerce, $post;
$productsList = new WP_Query( 'post_type=product&post_status=publish');
?>
<div class="inside">
<table class="form-table">
<input type="hidden" name="inventory_noncename" id="inventory_noncename" value="<?php wp_create_nonce( 'inventory-nonce' ); ?>" />
<?php
while ( $productsList->have_posts() ) {
$productsList->the_post();
?>
<tr><td><label for="location_inventory_product-<?php the_ID(); ?>"><?php the_title(); ?></label></td><td><input id="location_inventory_product-<?php the_ID(); ?>" name="location_inventory_product-<?php the_ID(); ?>" cols="40" rows="5" value="<?php echo $meta_key; ?>" /></td></tr>
<?php }
wp_reset_postdata();
?>
</table>
</div>
<?php
}
/*update on save*/
add_action('save_post', 'save_postdata_dynamic_inventory_metabox' );
function save_postdata_dynamic_inventory_metabox( $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;
}
// Check permissions
if ( 'location_inventory' == $_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;
}
// verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
if (isset($_POST['inventory_noncename'])){
if ( !wp_verify_nonce( $_POST['inventory_noncename'], 'inventory-nonce' ) )
return;
} else {
return;
}
// Get the posted data and sanitize it for use as an HTML class.
$new_meta_value = ( isset( $_POST['location_inventory_product-'.the_ID().''] ) ? sanitize_html_class( $_POST['location_inventory_product-'.the_ID().''] ) : '' );
// Get the meta key.
$meta_key = 'location_inventory_product-'.the_ID().'';
// 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 );
} // ends function save_postdata_dynamic_reviews_metabox
Some observations:
1) The hook save_post takes 2 arguments:
add_action( 'save_post', 'save_postdata_dynamic_inventory_metabox', 10, 2 );
function save_postdata_dynamic_inventory_metabox( $post_id, $post_object ) { }
2) I don't think checking for permissions is necessary (at least, never seen it). Just in case, this is an example of the post_object use:
if ( 'location_inventory' == $post_object->post_type )
3) Short this check:
if ( !isset($_POST['inventory_noncename']) || !wp_verify_nonce( $_POST['inventory_noncename'], 'inventory-nonce' ) )
return;
4) The use of the_ID() inside the function save_postdata_dynamic_inventory_metabox is wrong. This is only available inside a Loop and you already have $post_id at hand.
5) Finally, and the most important, the way you're handling the $meta_key is wrong. For one, it's not defined inside the function my_metabox_render. Check this Answer for a working example.
Research in this search query to find more examples.
Okay let me see if I can explain this right. In wordpress we have a box to insert an excerpt. We need to add a second excerpt box. Instead of manually adding a custom field to every post I have placed a function to automatically add a custom field in the form of a Meta box on the admin post page.
Okay so this is the problem that i'm having this function is working except for the fact that whatever you enter into this field it loses it's line breaks. So when our writers are contrubuting to this field in order to keep formatting of the block of text I have to manually add to the end of the paragraph.
Here is my code:
function my_create_post_meta_box() {
add_meta_box( 'my-meta-box', 'Second Excerpt', 'my_post_meta_box', 'post', 'normal', 'high' );
}
function my_post_meta_box( $object, $box ) { ?>
<p>
<label for="second-excerpt">
<strong>Second Excerpt With Images for Post List Page</strong>
</label>
<textarea name="second-excerpt" id="second-excerpt" cols="60" rows="4" tabindex="30" style="width: 97%;" wrap="hard"><?php echo wp_specialchars( get_post_meta( $object->ID, 'Second Excerpt', true ), 1 ); ?></textarea>
<input type="hidden" name="my_meta_box_nonce" value="<?php echo wp_create_nonce( plugin_basename( __FILE__ ) ); ?>" />
</p>
<?php
}
function my_save_post_meta_box( $post_id, $post ) {
if ( !wp_verify_nonce( $_POST['my_meta_box_nonce'], plugin_basename( __FILE__ ) ) )
return $post_id;
if ( !current_user_can( 'edit_post', $post_id ) )
return $post_id;
$meta_value = get_post_meta( $post_id, 'Second Excerpt', true );
$new_meta_value = stripslashes( $_POST['second-excerpt'] );
if ( $new_meta_value && '' == $meta_value )
add_post_meta( $post_id, 'Second Excerpt', $new_meta_value, true );
elseif ( $new_meta_value != $meta_value )
update_post_meta( $post_id, 'Second Excerpt', $new_meta_value );
elseif ( '' == $new_meta_value && $meta_value )
delete_post_meta( $post_id, 'Second Excerpt', $meta_value );
}
Thanks and any help would do.
Use wpautop function on frontend template. Like:
<?php $yourvalue = get_post_meta($post->ID, "yourvalue", true);
if ($yourvalue != ""){ ?>
<dt>Consultório:</dt>
<dd><?php echo wpautop( $consultorio, $br = 1 ); ?></dd>
<?php } ?>
Just add this line after $new_meta_value = ...:
$new_meta_value = nl2br($new_meta_value);
And instead of comparing your values to '', it's better to use empty(). Also some of the comparisons are unneeded. Thus, the add/update/delete part of your save function can be written like this:
if(empty($meta_value)) {
add_post_meta( $post_id, 'Second Excerpt', $new_meta_value, true );
} elseif(empty($new_meta_value)) {
delete_post_meta( $post_id, 'Second Excerpt', $meta_value );
} else {
update_post_meta( $post_id, 'Second Excerpt', $new_meta_value );
}
Note that it's always advisable to use curly braces even if your statement is only one row long. It improves readability and doesn't mess things up if/when you have to add another row to the if clause.
Don't modify the data saved to the database. Save exactly what the user enters. Instead modify the content when you need to display it. This way when the user comes back to edit the field the edit what they put in, not what you've made of their content.
Use wpautop to do the same translation on your text that WordPress applies to the raw content entered in the post-content field and do it when the content is requested for display.
Okay I have found another solution to my problem. Thank you Tatu for getting my brain workin. For those who are looking for a solution this is what I did:
$new_meta_value = "<p>" . implode( "</p>\n\n<p>", preg_split( '/\n(?:\s*\n)+/', $new_meta_value ) ) . "</p>";