WP Metabox not saving post meta - php

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');

Related

On WordPress metabox How to Keep the checked radio button checked after updating post

I created a metabox that can be used to add a sidebar to a post. The get_sidebar function will be added to the post template using an if statement based on whether the user checks the sidebar radio button or not, but I haven't got that far yet.
So far the metabox shows up in the editor screen but when I check the sidebar radio button it returns unchecked after I update the post.
This is what I am using to keep the radio button checked after the post has been updated.
$layout = $_POST["layout"];
<input type="radio" name="layout" <?php if (isset($layout) && $layout=="right-sidebar") echo "checked"; ?> value="right-sidebar">
This is the full code I am using to create and update the metabox:
<?php
function hill_add_layout_metabox() {
add_meta_box(
'layout_metabox',
'Layout1',
'hill_callback_layout_matabox',
'post',
'side',
'high'
);
}
add_action('add_meta_boxes', 'hill_add_layout_metabox');
function hill_callback_layout_matabox() {
$layout = $_POST["layout"];
?>
<input type="radio" name="layout" <?php if (isset($layout) && $layout=="right-sidebar") echo "checked"; ?> value="right-sidebar"> Right Sidebar
<?php
}
function hill_save_layout_metabox($post_id) {
$is_autosave = wp_is_post_autosave ( $post_id );
$is_revision = wp_is_post_revision ( $post_id );
if ( $is_autosave || $is_revision ) {
return;
}
$layout = $_POST["layout"];
if (isset($layout) && $layout=="right-sidebar") {
update_post_meta( $post_id, $layout );
}
}
add_action('save_post', 'hill_save_layout_metabox');
?>
How to add custom meta box in post . Refer the below links it will solved your problem .
https://www.smashingmagazine.com/2011/10/create-custom-post-meta-boxes-wordpress/
http://code.tutsplus.com/tutorials/how-to-create-custom-wordpress-writemeta-boxes--wp-20336
http://www.sitepoint.com/adding-custom-meta-boxes-to-wordpress/
First, when saving the meta value, add a value to be saved:
It's a matter of preference, but I'll set the value to 'on' if checked other wise ''.
$value = isset($layout) && $layout=='right-sidebar' ? 'on' : ''
update_post_meta( $post_id, 'right-sidebar', $value );
After updating the post, get the value you saved using get_post_meta and set the radio button if needed; the WP checked() function is handy for this:
<?php $check = get_post_meta( $post_id, 'right-sidebar', true ); ?>
<input type="radio" name="layout" <?php checked( $check, 'on' ); ?> value="right-sidebar">

Undefined variable: post in

I'm debugging my wordpress theme and I keep getting this notification in my functions.php file:
Undefined variable: post in (myfolders)/functions.php on line 961
This is line 961
echo apply_filters('the_content', get_post_meta($post->ID, 'mpc_projects_description', true));
The code is for a custom tinymce for my custom post type(Portfolio) project description.
What is causing variable to be undefined? Here is the code in it's entirety:
add_action( 'add_meta_boxes', 'mpc_add_description_meta_box' );
// Add the projects Meta Box
function mpc_add_description_meta_box() {
add_meta_box('mpc_add_description_meta_box', 'Project Description', 'mpc_add_description_meta_box_callback', 'portfolio', 'normal', 'high');
}
// the description output
function mpc_add_description_meta_box_callback() {
global $post;
// Noncename needed to verify where the data originated
echo '<input type="hidden" name="mpc_projects_description_noncename" id="mpc_projects_description_noncename" value="'.wp_create_nonce(plugin_basename(__FILE__)).'" />';
// Get the location data if its already been entered
$input = get_post_meta($post->ID, 'mpc_projects_description', true);
// echo '<input type="text" name="mpc_projects_description" value="' . $input . '" " />';
wp_editor($input, 'mpc_projects_description', array('textarea_name' => 'mpc_projects_description', 'editor_css' => '<style>#wp-mpc_projects_description-editor-container{background-color:white;style="width:100%;}</style>'));
echo '<table id="post-status-info" cellspacing="0"><tbody><tr><td id="wp-word-count">Word count: <span class="word-count_2">';
$words = strip_tags($input);
$count = str_word_count($words, 0);
echo $count;
echo '</span></td>
<td class="autosave-info">
<span class="autosave-message"> </span>
</td>
</tr></tbody></table>';
}
//save the data
add_action('save_post', 'mpc_save_description_meta', 1, 2); // save the custom fields
function mpc_save_description_meta($post_id, $post) {
// 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['mpc_projects_description_noncename'], plugin_basename(__FILE__) )) {
return $post->ID;
}
// Is the user allowed to edit the post or page?
if ( !current_user_can( 'edit_post', $post->ID ))
return $post->ID;
// OK, we're authenticated: we need to find and save the data
// We'll put it into an array to make it easier to loop though.
$mpc_description_meta['mpc_projects_description'] = $_POST['mpc_projects_description'];
// Add values of $mpc_description_meta as custom fields
foreach ($mpc_description_meta as $key => $value) { // Cycle through the $mpc_description_meta array!
if( $post->post_type == 'revision' ) return; // Don't store custom data twice
$value = implode(',', (array)$value); // If $value is an array, make it a CSV (unlikely)
if(get_post_meta($post->ID, $key, FALSE)) { // If the custom field already has a value
update_post_meta($post->ID, $key, $value);
} else { // If the custom field doesn't have a value
add_post_meta($post->ID, $key, $value);
}
if(!$value) delete_post_meta($post->ID, $key); // Delete if blank
}
}
echo apply_filters('the_content', get_post_meta($post->ID, 'mpc_projects_description', true));
The post global is available inside the functions but you haven't set it outside.
Change:
echo apply_filters('the_content', get_post_meta($post->ID, 'mpc_projects_description', true));
To:
global $post;
echo apply_filters('the_content', get_post_meta($post->ID, 'mpc_projects_description', true));
This could also depend on where you use this code. If you fire the code before the post object is set then you'll get this error.
If it's just in functions.php then change it to:
function wpse_post_test() {
global $post;
echo apply_filters('the_content', get_post_meta($post->ID, 'mpc_projects_description', true));
}
add_action( 'wp', 'wpse_post_test' );
After reviewing your question again it appears you are attempting to output this inside functions.php. What are you trying to achieve?

Wordpress WooCommerce text attribute

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');
}

How to display the terms in a dropdown list in the admin option in wordpress

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');

How to save a checkbox meta box in WordPress?

I'm trying to add a checkbox into my custom meta box in WordPress and I ran into a problem with saving it - whenever I check the checkbox and update the post/page, it comes back unchecked again.
Here's the code I'm using:
add_meta_box(
'sl-meta-box-sidebar', // id
'Sidebar On/Off', // title
'sl_meta_box_sidebar', // callback function
'page', // type of write screen
'side', // context
'low' // priority
);
function sl_meta_box_sidebar() {
global $meta; sl_post_meta( $post->ID ); ?>
<input type="checkbox" name="sl_meta[sidebar]" value="<?php echo htmlspecialchars ($meta['sidebar']); ?>" />Check to turn the sidebar <strong>off</strong> on this page.
}
This creates the checkbox in the sidebar of the "Edit Page" screen, as it should, no problem there. I'm not sure what should I enter in the value of the checkbox, with text fields it obviously returns whatever was saved as meta information... I tried just using "checked" instead cause that would be my first guess (then simply check for the value when using this meta data), but it didn't save the checkbox either.
Here's the function that saves all the meta data, which I assume causes this problem:
function sl_save_meta_box( $post_id, $post ) {
global $post, $type;
$post = get_post( $post_id );
if( !isset( $_POST[ "sl_meta" ] ) )
return;
if( $post->post_type == 'revision' )
return;
if( !current_user_can( 'edit_post', $post_id ))
return;
$meta = apply_filters( 'sl_post_meta', $_POST[ "sl_meta" ] );
foreach( $meta as $key => $meta_box ) {
$key = 'meta_' . $key;
$curdata = $meta_box;
$olddata = get_post_meta( $post_id, $key, true );
if( $olddata == "" && $curdata != "" )
add_post_meta( $post_id, $key, $curdata );
elseif( $curdata != $olddata )
update_post_meta( $post_id, $key, $curdata, $olddata );
elseif( $curdata == "" )
delete_post_meta( $post_id, $key );
}
do_action( 'sl_saved_meta', $post );
}
add_action( 'save_post', 'sl_save_meta_box', 1, 2 );
It works perfectly for text fields, but the checkbox just won't save. I'm not sure if the saving function is wrong, or am I missing something about the value of the checkbox.
Any help appreciated!
I had trouble with this previously and here is how I solved it.
First, creating the Checkbox.
<?php
function sl_meta_box_sidebar(){
global $post;
$custom = get_post_custom($post->ID);
$sl_meta_box_sidebar = $custom["sl-meta-box-sidebar"][0];
?>
<input type="checkbox" name="sl-meta-box-sidebar" <?php if( $sl_meta_box_sidebar == true ) { ?>checked="checked"<?php } ?> /> Check the Box.
<?php } ?>
Next, saving.
<?php
add_action('save_post', 'save_details');
function save_details($post_ID = 0) {
$post_ID = (int) $post_ID;
$post_type = get_post_type( $post_ID );
$post_status = get_post_status( $post_ID );
if ($post_type) {
update_post_meta($post_ID, "sl-meta-box-sidebar", $_POST["sl-meta-box-sidebar"]);
}
return $post_ID;
} ?>

Categories