Update post meta from frontend of different page - php

I'm trying to update the post content of a specified posttype. For some reason it's not working.
I have already successfully used the code in the backend in the mail page for editing. Now I want to use it also in the frontend for employees for quick administration.
$id is transferred correctly. I used this code
This is my code snippet:
<?php $id = $_GET['car']; ?>
<?php
if ( isset( $_POST['submit'] ) ){
$fields = [
'car-highlight-2',
];
foreach ( $fields as $field ) {
if ( array_key_exists( $field, $_POST ) ) {
update_post_meta( $id, $field, sanitize_text_field( $_POST[$field] ) );
}
}}
?>
<form method="post" action="">
<tr>
<td><input type="text" id="car-highlight-2" name="car-highlight-2" value="<?php echo get_post_meta($id, 'car-highlight-2', true); ?>"></td>
</tr>
<input type='submit' value='save' />
</form>

I forgot to add name="submit" to the input.

Related

Display categories of a Custom post type in WooCommerce product

I have created a custom post type with own categories.
I would like to link the categories of the custom post type to the WooCommerce product. e.g. This product belongs to the category Fabric cover.
These categories I have displayed in Woocommerce products in the backend.
I do that with getterm. So far, everything works. I then created a checkbox field in front of each category.
When I save the contents, all categories are stored in an array (whether I've selected it or not). I would like to save only the category I have selected. What am I doing wrong?
how can I just save the array of the selected checkbox in metabox (pro_in_cat_fields).
At the moment all values are saved. If I only check one checkbox (for example, fabric cover1), only the values that are in the same array of the checkbox need to be saved. not the values of fabric cover 1, fabric cover 2, ... etc
<?php
add_action('admin_init', 'add_pro_in_cat_boxes', 1);
function add_pro_in_cat_boxes() {
add_meta_box( 'pro_in_cat-fields', 'Save product in custom category', 'pro_in_cat_meta_box_display', 'product', 'normal', 'low');
}
function pro_in_cat_meta_box_display() {
global $post;
$pro_in_cat_fields = get_post_meta($post->ID, 'pro_in_cat_fields', true);
wp_nonce_field( 'pro_in_cat_meta_box_nonce', 'pro_in_cat_meta_box_nonce' );
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('.pro_in_cat_submit').click(function(e) {
e.preventDefault();
$('#publish').click();
});
});
</script>
<table id="pro_in_cat-fieldset-one" width="100%">
<thead>
<tr>
<th width="30%"></th>
<th width="70%"></th>
</tr>
</thead>
<tbody>
<?php
$stoffcat_parent= get_terms( 'cover_cat', array( 'hide_empty' => false, 'parent' => 0 ) );
if ( $stoffcat_parent ) :
foreach( $stoffcat_parent as $parent_term ) {
echo $parent_term->name . '<br>';
$stoffcat_value = get_terms( 'cover_cat', array( 'hide_empty' => false, 'parent' => $parent_term->term_id ) );
foreach( $stoffcat_value as $child_term ) {
?>
<tr>
<td>
<input type="checkbox" class="widefat" name="pro_in_cat_status[]" value="<?php echo $checked; ?>" />
<input type="text" class="widefat" name="pro_in_cat_name[]" value="<?php if($child_term->name != '') echo esc_attr( $child_term->name ); ?>" /></td>
<td><input type="text" class="widefat" name="pro_in_cat_termid[]" value="<?php if($child_term->term_id != '') echo esc_attr( $child_term->term_id ); ?>" />
<input type="text" class="widefat" name="pro_in_cat_slug[]" value="<?php if($child_term->slug != '') echo esc_attr( $child_term->slug); ?>" /></td>
</tr>
<?php
}
}
else :
// show a blank one
?>
<tr>
<td><input type="checkbox" class="widefat" name="pro_in_cat_status[]" />
<input type="text" class="widefat" name="pro_in_cat_name[]" /></td>
<td><input type="text" class="widefat" name="pro_in_cat_termid[]" /><input type="text" class="widefat" name="pro_in_cat_slug[]" /></td>
</tr>
<?php endif; ?>
</tbody>
</table>
<p>
<input type="submit" class="pro_in_cat_submit" value="Save" />
</p>
<?php
}
add_action('save_post', 'pro_in_cat_meta_box_save');
function pro_in_cat_meta_box_save($post_id) {
if ( ! isset( $_POST['pro_in_cat_meta_box_nonce'] ) ||
! wp_verify_nonce( $_POST['pro_in_cat_meta_box_nonce'], 'pro_in_cat_meta_box_nonce' ) )
return;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return;
if (!current_user_can('edit_post', $post_id))
return;
$pro_in_catold = get_post_meta($post_id, 'pro_in_cat_fields', true);
$pro_in_catnew = array();
$pro_in_catstatus = $_POST['pro_in_cat_status'];
$pro_in_catnames = $_POST['pro_in_cat_name'];
$pro_in_cattermid = $_POST['pro_in_cat_termid'];
$pro_in_catslug = $_POST['pro_in_cat_slug'];
$count = count( $pro_in_catnames );
for ( $i = 0; $i < $count; $i++ ) {
if ( $pro_in_catstatus[$i] != '' ) {
$pro_in_catnew[$i]['pro_in_cat_status'] = stripslashes( strip_tags( $pro_in_catstatus[$i] ) );
}
if ( $pro_in_catnames[$i] != '' ) {
$pro_in_catnew[$i]['pro_in_cat_name'] = stripslashes( strip_tags( $pro_in_catnames[$i] ) );}
if ( $pro_in_cattermid[$i] != '' ) {
$pro_in_catnew[$i]['pro_in_cat_termid'] = stripslashes( strip_tags( $pro_in_cattermid[$i] ) );}
if ( $pro_in_catslug[$i] != '' ) {
$pro_in_catnew[$i]['pro_in_cat_slug'] = stripslashes( strip_tags( $pro_in_catslug[$i] ) );}
}
if ( !empty( $pro_in_catnew ) && $pro_in_catnew != $pro_in_catold )
update_post_meta( $post_id, 'pro_in_cat_fields', $pro_in_catnew );
elseif ( empty($pro_in_catnew) && $pro_in_catold )
delete_post_meta( $post_id, 'pro_in_cat_fields', $pro_in_catold );
}

Fill input with array

In my jquery code I have:
$("#show").append("<img src=" +attachment.url+" alt="+attachment.alt+" title="+attachment.title+" description="+attachment.caption+" class='img-responsive img-thumbnail'/><input type='hidden' name='my_image_URL[]' value="+attachment.url+"></span>");
My jquery code adds fields for news selected images and fills inputs names my_image_URL[].
In PHP:
if ( isset( $_POST['my_image_URL'] ) ) {
$urls = $_POST['my_image_URL'];
echo '<input type="hidden" name="imagens_home" value="'.$urls.'"/>';
}
I trying to add $urls array in the hidden input.
And after, if its works ok:
<?php
if ($urls != '' ) {
foreach ($urls as $url) {
?>
<img src="<?php echo $url;?>" class="img-responsive img-thumbnail " />
<input name="my_image_URL[]" value="<?php echo $url;?>"/>
</div>
<?php
};
}
?>
But this part of code not fill the input:
if ( isset( $_POST['my_image_URL'] ) ) {
$urls = $_POST['my_image_URL'];
echo '<input type="hidden" name="imagens_home" value="'.$urls.'"/>';
}
---------- UPDATE --------
options.php
register_setting(
'tema-setting-group',//string $option_group
'imagens_home' //string $option_name
//calback $sanitize_calback
);
---
add_settings_field(
'home-imagens-top',//string $id
'Imagens',//String $title
'tema_home_imgs',//string $calback
'opcoes_do_tema',//string $page
'tema-home-options'//string $section
//string $args
);
//calback
function tema_home_imgs(){
$urlsImagens = esc_attr( get_option( 'imagens_home' ) ); // RETURN DB DATA
include( get_template_directory() . '/inc/templates/selecao_imagens.php');
if ( isset( $_POST['my_image_URL'] ) ) {
$urls = $_POST['my_image_URL'];
echo '<input name="imagens_home" value="'.$json_encode($urls).'" style="width:300px"/>';
}
}
selecao_imagens.php
<input id="my_upl_button" type="button" value="Escolher Imagens" /><br/>
<div class="row">
<div id="exibe" class="sortable">
<?php
$urls = json_decode($urlsImagens, true);
if ($urls != '' ) {
foreach ($urls as $url) {
?>
<img src="<?php echo $url;?>" class="img-responsive img-thumbnail " />
<input name="my_image_URL[]" value="<?php echo $url;?>"/>
<?php
};
}
?>
</div>
</div>
theme_options.php
<?php settings_errors();?>
<form method="post" action="options.php">
<?php settings_fields ('tema-setting-group'); ?>
<?php do_settings_sections (
'opcoes_do_tema'//string $page
); ?>
<?php submit_button ();
?>
</form>
-------- UPDATE 2 -------
I tried:
echo '<input name="imagens_home" value="' . htmlspecialchars(json_encode($urls)) . '" />';
but it is not yet filling in the input.
I also tried only:
If (isset ($ _POST ['my_image_URL'])) {
Print_r ($ _ POST ['my_image_URL']);
}
But after the submit does not appear anything on the screen, in the form correctly saves all other inputs except what I am trying to save the array, if I put some manual information goes ok. But I do not understand why it is not capturing the my_image_URL [] names of each image input. The action in form is like this:
<Form method = “post” action = “options.php”>
I’m using the Settings API
Thanks
I trying to add $urls array in the hidden input.
If I understand, you're trying to store an array value in a hidden input, so you can retrieve it later. Problem is, this doesn't work...
echo '<input type="hidden" name="imagens_home" value="'.$urls.'"/>';
...because when you echo a PHP array all you get is the string Array, not the actual array contents.
You could turn the array into a json string though:
echo '<input type="hidden" name="imagens_home" value="'.$json_encode($urls).'"/>';
Now your hidden input has a regular string. Later, when the form is POSTed, you could retrieve it:
$urls = json_decode($_POST['imagens_home'], true)

Wordpress Checkbox never updates on profile page

Totally stumped. I have a checkbox on the user profile page but it refuses to update. Its not even an array set value or anything, just never sets...Seems like no data gets passed to the post value...
updated as per #RST and now as per #simon-pollard
// This will show below the color scheme and above username field
add_action( 'profile_personal_options', 'extra_profile_fields' );
add_action( 'personal_options_update', 'update_field_value' );
add_action( 'edit_user_profile_update', 'update_field_value' );
function extra_profile_fields( $user ) {
// get the value of a single meta key
$user_id = $user->ID;
echo "user id: " . $user_id . "<br/>";
$meta_value = get_user_meta( $user->ID, 'emailPrefs', true ); // $user contains WP_User object
// do something with it.
echo "checked value: " . $meta_value. "<br/>";
?>
<h2>Email Settings</h2>
<table class="form-table">
<th scope="row" id="lbl-subtitle" for="email-settings">Email on Timer Reset</th>
<td><fieldset>
<form method='post' action="profile.php">
<input type="checkbox" id="email-settings" name='email-settings'
<?php if ($meta_value == '1'){ echo 'checked'; } ?> value ="<?php echo $meta_value?>" />
</form>
<?php submit_button(); ?>
</td>
</fieldset>
</table>
<?php
}
function update_field_value($user) {
$user_id =$user->ID;
if (isset($_POST['email-settings']) && $_POST['email-settings'] == 'on') {
update_user_meta( $user_id, 'emailPrefs', '1');
} else {
update_user_meta( $user_id, 'emailPrefs', NULL);
}
}
Thanks #Simon. With his help, I saw that the $user object was not accessible on that update hook meaning the user_meta never updated. To work around this I've created a hidden form field to store my userID so that it's available as a post variable.
Here is the Final Code:
// This will show below the color scheme and above username field
add_action( 'profile_personal_options', 'extra_profile_fields' );
add_action( 'personal_options_update', 'update_field_value' );
add_action( 'edit_user_profile_update', 'update_field_value' );
function extra_profile_fields( $user ) {
// get the value of a single meta key
$user_id = $user->ID;
echo "user id: " . $user_id . "<br/>";
$meta_value = get_user_meta( $user->ID, 'emailPrefs', true ); // $user contains WP_User object
// do something with it.
echo "checked value: " . $meta_value. "<br/>";
?>
<h2>Email Settings</h2>
<table class="form-table">
<th scope="row" id="lbl-subtitle" for="email-settings">Email on Timer Reset</th>
<td><fieldset>
<form method='post' action="profile.php">
<input type='hidden' name="user_id" value="<?php echo $user_id ?>" />
<input type="checkbox" id="email-settings" name='email-settings'
<?php if ($meta_value == '1'){ echo 'checked'; } ?> />
</form>
<?php submit_button(); ?>
</td>
</fieldset>
</table>
<?php
}
function update_field_value($user_id) {
$user_id = $_POST['user_id'];
// echo $user_id;
// echo $_POST['email-settings'];
// wp_die();
if ( isset($_POST['email-settings'], $_POST['user_id'] ) && $_POST['email-settings'] == 'on') {
update_user_meta( $user_id, 'emailPrefs', '1');
} else {
update_user_meta( $user_id, 'emailPrefs', NULL);
}
}
Leaving in the commented out portion so future readers can check this for themselves.

How to get Text Area in WordPress posts section?

I need to change this code to implement "More info" field as a text field in my WordPress post section.
The "More info" field looks like this:
I use smartmetabox. It has 2 files:
textarea.php:
<textarea name="<?php echo $id?>" id="<?php echo $id?>" rows="5" cols="100" class="custom"><?php echo $value?></textarea>
text.php:
<input type="text" name="<?php echo $id?>" id="<?php echo $id?>" value="<?php echo $value?>" class="regular-text" />
And my_file.php code is:
<?php
add_action( 'add_meta_boxes', 'cd_meta_box_add' );
function cd_meta_box_add()
{
add_meta_box( 'my-meta-box-id', __('Information', 'addict'), 'cd_meta_box_cb', 'post', 'normal', 'high' );
}
function cd_meta_box_cb( $post )
{
$values = get_post_custom( $post->ID );
$creteria_1_text = isset( $values['creteria_1_text'] ) ? esc_attr( $values['creteria_1_text'][0] ) : '';
$check = isset( $values['my_meta_box_check'] ) ? esc_attr( $values['my_meta_box_check'][0] ) : '';
wp_nonce_field( 'my_meta_box_nonce', 'meta_box_nonce' );
?>
<p>
<label for="creteria_1_text"><b><?php _e("More info, 'addict') ?></b></label>
<input style="width:85%" type="text" name="creteria_1_text" id="creteria_1_text" value="<?php echo $creteria_1_text; ?>" />
</p>
<?php
}
add_action( 'save_post', 'cd_meta_box_save' );
function cd_meta_box_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['creteria_1_text'] ) )
update_post_meta( $post_id, 'creteria_1_text', wp_kses( $_POST['creteria_1_text'], $allowed ) );
}
// function for show rating content
//$key_1_value = get_post_meta($post->ID, 'my_meta_box_text', true);
?>
After some digging i found that i should replace this code:
<input style="width:85%" type="text" name="creteria_1_text" id="creteria_1_text" value="<?php echo $creteria_1_text; ?>
To:
<textarea name="creteria_1_text" id="creteria_1_text" rows="5" cols="100" class="custom"><?php echo $creteria_1_text; ?></textarea>

default value not getting displayed in input field wordpress

I have written code for creating theme options
but default values not getting displayed in text field
Also settings saved message also not getting displayed
Thank you
<?php
// Default options values
$xyz_options = array(
'footer_copyright' => '© ' . date('Y') . ' ' . get_bloginfo('name'),
'facebook'=>'http://www.facebook.com/'
);
if ( is_admin() ) : // Load only if we are viewing an admin page
function xyz_register_settings() {
// Register settings and call xyz initiation functions
register_setting( 'xyz_theme_options', 'xyz_options', 'xyz_validate_options' );
}
add_action( 'admin_init', 'xyz_register_settings' );
function xyz_theme_options() {
// Add theme options page to the admin menu
add_theme_page( 'Theme Options', 'Theme Options', 'edit_theme_options', 'theme_options', 'xyz_theme_options_page' );
}
add_action( 'admin_menu', 'xyz_theme_options' );
// Function to generate options page
function xyz_theme_options_page() {
global $xyz_options;
if ( ! isset( $_REQUEST['updated'] ) )
$_REQUEST['updated'] = false; // This checks whether the form has just been submitted. ?>
<div class="wrap">
<?php screen_icon(); echo "<h2>" . get_current_theme() . __( ' Options' ) . "</h2>";
// This shows the page's name and an icon if one has been provided ?>
<?php if ( false !== $_REQUEST['updated'] ) : ?>
<div class="updated fade"><p><strong><?php _e( 'Options saved' ); ?></strong></p></div>
<?php endif; // If the form has just been submitted, this shows the notification ?>
<form method="post" action="options.php">
<?php $settings = get_option( 'xyz_options', $xyz_options ); ?>
<?php settings_fields( 'xyz_theme_options' );
/* This function outputs some hidden fields required by the form,
including a nonce, a unique number used to ensure the form has been submitted from the admin page
and not somewhere else, very important for security */ ?>
<table class="form-table">
<tr valign="top">
<th scope="row">
<label for="facebook">Facebook url</label>
</th>
<td>
<input id="facebook" name="xyz_options[facebook]" type="text" value="<?php esc_attr_e($settings['facebook']); ?>" />
</td>
</tr>
<tr valign="top">
<th scope="row">
<label for="footer_copyright">Footer Text 1</label>
</th>
<td>
<input id="footer_copyright" name="xyz_options[footer_copyright]" type="text" value="<?php esc_attr_e($settings['footer_copyright']); ?>" />
</td>
</tr>
</table>
<p class="submit">
<input type="submit" class="button-primary" value="Save Options" />
</p>
</form>
</div>
<?php
}
function xyz_validate_options( $input ) {
global $xyz_options;
$settings = get_option( 'xyz_options', $xyz_options );
}
endif; // EndIf is_admin()
I have wriiten above code.
Please help
Thank you
I tested your code and the default values are being displayed correctly.
Doing a var_dump($_REQUEST); shows what's the problem with the update message, we have to check simpy for $_REQUEST['settings-updated'].
You can remove the is_admin() checking, as admin_init and admin_menu only run on admin.
The validation function should be something like this, validating each input field and returning a clean array with sanitized values:
function xyz_validate_options( $input ) {
$new_input = array();
if( isset( $input['facebook'] ) )
$new_input['facebook'] = esc_url( $input['facebook'] );
if( isset( $input['footer_copyright'] ) )
$new_input['footer_copyright'] = esc_attr( $input['footer_copyright'] );
return $new_input;
}

Categories