I've created some custom fields on the user profile page in WordPress.
I've managed to build a front end editor for the user to change some e-mail preferences:
<?php if( isset($_POST['preferences']) ) :
update_field('planner-reminders', $_POST['planner-reminders'], 'user_'.$user_id.'');
update_field('event-suggestions', $_POST['event-suggestions'], 'user_'.$user_id.'');
update_field('woa-updates', $_POST['woa-updates'], 'user_'.$user_id.'');
echo '<p class="success">E-Mail Prefereneces Updated<p>';
endif; ?>
<form action="<?php the_permalink(); ?>" method="POST" class="user-email-settings">
<!-- planner reminders -->
<?php
$field = get_field('planner-reminders', 'user_'.$user_id.'');
if( $field == true ) {
$field = '1';
$checked = true;
}
?>
<input type="checkbox" id="planner-reminders" name="planner-reminders" class="pref"
value="<?php echo $field; ?>" <?php if($checked) :?> checked <?php endif;?> />
<label for="planner-reminders">I don't want to revieve reminders about events I've added to my planner.</label>
<?php $checked = false; ?>
<!-- event suggestions from WOA -->
<?php
$field = get_field('event-suggestions', 'user_'.$user_id.'');
if( $field == true ) {
$field = '1';
$checked = true;
}
?>
<input type="checkbox" id="event-suggestions" name="event-suggestions" class="pref"
value="<?php echo $field; ?>" <?php if($checked) :?> checked <?php endif;?> />
<label for="event-suggestions">I don't want to recieve suggestions about events I may be interested in.</label>
<?php $checked = false; ?>
<!-- updates from WOA -->
<?php
$field = get_field('woa-updates', 'user_'.$user_id.'');
if( $field == true ) {
$field = '1';
$checked = true;
}
?>
<input type="checkbox" id="woa-updates" name="woa-updates" class="pref"
value="<?php echo $field; ?>" <?php if($checked) :?> checked <?php endif;?> />
<label for="woa-updates">I don't want to recieve e-mail updates from What's On Advisor.</label>
<?php $checked = false; ?>
<input type="submit" value="Save Preferences" name="preferences" id="preferences" />
</form>
Now, this actually seems to work. If I update a checkbox it shows and checked/unchecked as it should, and it shows correctly in the front end and the back end.
But, when I try to query this setting with a wp_query to actually send the e-mails to those who haven't opted out, it bug out a little.
If the user opts out, then opts back in, the wp_query doens't pick them up. It only picks them up when I go into the wp-admin area and update their user profile. I don't actually have to change anything, just open the user up and click update.
Here's the wp_query just incase:
<?php $args = array(
'role' => 'Subscriber',
'meta_key' => 'planner-reminders',
'meta_value' => '0',
'meta_compare' => '=='
); ?>
<?php $user_query = new WP_User_Query( $args ); ?>
<?php if ( ! empty( $user_query->results ) ) : ?>
etc. etc.
Any ideas how I can get this working properly? Is there a function to fake a click on the 'Update User' button in wp-admin?
Thanks.
When the user opts out, the $field value will be empty, and therefore the value-attribute of the checkboxes will be empty. I haven't fully tested it, but this can yield unexpected behaviour in your setup. When a form with an unchecked checkbox is submitted through a POST request, the checkbox name will not be set in the $_POST array, which is why you should, in this case, set the value-attribute of the checkboxes to "1", so it is properly stored via update_field.
Could you try changing the checkbox values in the code posted above to "1" for the checkbox input elements? That would be value="1" instead of value="<?php echo $field; ?>".
To prevent PHP notices being generated for inexistent array keys, I would advise to change
update_field('planner-reminders', $_POST['planner-reminders'], 'user_'.$user_id.'');
to
update_field('planner-reminders', empty( $_POST['planner-reminders'] ) ? '0' : '1', 'user_'.$user_id.'');
as well.
Related
I am trying to create a button "Approved" to change the post category from it's current one to the "approved" category. I don't mind if it reloads the page or not. I would also like to redirect the page afterward to the next post in the original category.
I have found some questions on this already but am ultimately lost on how to get this all together and working.
<?php add_shortcode('approved_button', 'brist_approved_button_function');
function brist_approved_button_function() {
ob_start(); ?>
<form method="post" action="approved.php">
<input type="submit" value="Approved" name="submit"> <!-- assign a name for the button -->
</form>
<?php
wp_set_object_terms( $post_id, intval( $_POST['approved'] ), 'category', false );
$output = ob_get_clean();
return $output;
}?>
I figured it out. Though it was a head-scratcher for me. If anyone else if having the same issue, note the code below. You have to create the select and then have the 'selected' option on the category you want the post to change to. Then, in the CSS, hide the select input, only leaving the button.
<?php add_shortcode('approved_button', 'approved_button_function');?>
<?php function approved_button_function() { ob_start();?>
<div class="approval">
<form action="" id="update-post" method="post">
<?php wp_dropdown_categories( "selected='categoryId'&exclude=21&class=approval-select&show_count=1&hierarchical=1&orderby=name&order=ASC&&hide_empty=0&show_option_all=Choose An Option" ); ?>
<input class="approval-button" type="submit" name="submit" value="Approve" />
</form>
</div>
<?php if ( array_key_exists('cat', $_POST )) {
global $post;
$post_id = $post->ID;
wp_set_object_terms( $post_id, intval( $_POST['cat'] ), 'category', false );
} ?>
I'm trying to add terms to my custom taxonomy from a front-end form. I managed to create the form populate the select by values from another custom post type's posts. But I think that my form handler is not working... When I hit submit the form just takes me to "http://therealaddress.com/wp-admin/admin-post.php" and nothing happens (no new term to the taxonomy, no forwarding to the page I want)... (and yes, I changed therealaddress.com to hide my real address, it's not the wrong address :D)
I would like to forward the user back to the page where the form is after the submission.
My form handling part looks like this in my themes funtions.php
function horse_taxonomy_adder() {
// splitting the select options value from "horses-real-name:Horses Real Name" to "horses-real-name" and "Horses Real Name"
$horsename = ( $_POST['horsename'] );
$hn_slug = split(':', $horsename)[0];
$hn_name = split(':', $horsename)[1];
wp_insert_term(
'hn_name', // the term
'hevoset', // the taxonomy
array(
'slug' => $hn_slug,
)
);
// add the admin notice
$admin_notice = "success";
// redirect the user to the page called "Hallinta"
$page = get_page_by_title('hallinta');
$this->wp_redirect(get_permalink($page->ID));
exit;
}
add_action('admin_post_add_horsetaxonomy','horse_taxonomy_adder');
My form looks like this:
<form action="http://therealaddress.com/wp-admin/admin-post.php" method="POST">
<input type="hidden" name="action" value="horse_taxonomy_adder">
<div class="form-group">
<label for="exampleInputEmail1">Valitse hevonen jolle päiväkirja luodaan</label>
<select name="horsename">
<?php
global $post;
$args = array( 'numberposts' => -1, 'post_type' => 'hevonen');
$posts = get_posts($args);
foreach( $posts as $post ) : setup_postdata($post); ?>
<option value="<? echo $post->post_name; ?>:<?php the_title(); ?>"><?php the_title(); ?></option>
<?php endforeach; ?>
</select>
</div>
<button type="submit" name="submit" class="btn btn-primary">Lisää päiväkirja</button>
</form>
I've created a variable within a function it looks like this:
function my_plugin_options() {
//must check that the user has the required capability
if (!current_user_can('manage_options'))
{
wp_die( __('You do not have sufficient permissions to access this page.') );
}
// variables for the field and option names
$opt_name = 'mt_favorite_color';
$hidden_field_name = 'mt_submit_hidden';
$data_field_name = 'mt_favorite_color';
// Read in existing option value from database
$opt_val = get_option( $opt_name );
doingthistest($opt_val);
// See if the user has posted us some information
// If they did, this hidden field will be set to 'Y'
if( isset($_POST[ $hidden_field_name ]) && $_POST[ $hidden_field_name ] == 'Y' ) {
// Read their posted value
$opt_val = $_POST[ $data_field_name ];
// Save the posted value in the database
update_option( $opt_name, $opt_val );
// Put a "settings saved" message on the screen
?>
<div class="updated"><p><strong><?php _e('settings saved.', 'help-menu-settings' ); ?></strong></p></div>
<?php
}
// Now display the settings editing screen
echo '<div class="wrap">';
// header
echo "<h2>" . __( 'Help block details', 'help-menu-settings' ) . "</h2>";
// settings form
?>
<form name="form1" method="post" action="">
<input type="hidden" name="<?php echo $hidden_field_name; ?>" value="Y">
<p><?php _e("Whatever:", 'menu-test' ); ?>
<input type="text" name="<?php echo $data_field_name; ?>" value="<?php echo $opt_val; ?>" size="20">
</p><hr />
<p class="submit">
<input type="submit" name="Submit" class="button-primary" value="<?php esc_attr_e('Save Changes') ?>" />
</p>
</form>
<span><?php echo $opt_val ?></span>
</div>
<?php
}
Now I can echo out the $opt_val variable within the scope of that function but i'm struggling to access it outside.
You'll see where I set the variable $opt_val = get_option( $opt_name ); below it I pass it to a function doingthistest($opt_val); then I create an action below so I can call it in another page (WordPress method).
So my action below looks like:
add_action('testingthis', 'doingthistest');
function doingthistest(t) {
var_dump(t);
}
for some reason, the variable isn't getting passed to my action. Am I misunderstanding something?
I call it in another page like this:
<span>info is there: <?php do_action( 'testingthis' ) ?></span>
if you want something to be available in a different page (therefore presumably during a different HTTP request?) then you'd have to put it into a session variable or other persistent storage (e.g. file, database) and the retrieve it from there in your other page. HTTP is inherently stateless and the server won't remember the value of your variables from one request to the next unless you use one of the above mechanisms to store them.
Calling doingthistest($opt_val); within the context of the code you posted will dump the variable onto that page. But then if you call that same method from another page entirely - which must by definition be in a different request - it doesn't automatically remember what you the value of it was last time. It's a separate request with a separate context.
I don't understand the Wordpress stuff precisely, but I suspect your action would be better looking something like this:
add_action('testingthis', 'doingthistest');
function dosomething($o) {
var_dump(get_option( $opt_name ));
}
But obviously you'd have to set the value of $opt_name somehow. In your sample code it's hard-coded but I don't know if that's really how you're setting it in the finished solution.
I have done foreach loop to get custom post type to frontend. And i have one custom field called 'order_staatus'. When i look in front end my list in loop, i want to add one button what would change this certain post 'order_staatus' to different value.. my code..
<? foreach ( $postslist as $post ) :
setup_postdata( $post );
?>
<div class="profile_order_row">
<?php the_author(); ?> <?php the_title(); ?>
<?php
Global $post;
if ( isset( $_POST['submit'] ) )
{
if( ! isset( $post ) ) {
echo 'Post not set';
die();
}
else if( ! isset( $_POST['staatus'] ) && ! empty( $_POST['staatus'] ) ){
echo 'Error';
die();
}
$postid = $_POST['post_id'];
update_post_meta($postid,'order_staatus','1');
}
$staatus = get_post_meta($post->ID, 'order_staatus', true);
echo print_r($staatus);
?>
<form method="post" action="">
<input type="hidden" name="post_id" value="'.$post->ID.'" />
<input type='text' name='staatus' value='<? echo $staatus ?>' />
<input type='submit' value='save' />
</form>
</div>
<?php endforeach; wp_reset_postdata(); ?>
I don't think the issue is with the function update_post_meta. I think the more likely issue is that $_POST['submit'] is not set. When submitting a form, the value of the submit button is not sent. The value attribute is simply for assigning the text of the button.
I would rewrite the IF block of code like this:
if ( isset( $_POST ) )
{
if( ! isset( $_POST['staatus'] ) && ! empty( $_POST['staatus'] ) ){
echo 'Error';
die();
}
$postid = sanitize_text_field($_POST['post_id']);
update_post_meta($postid,'order_staatus','1');
}
Note, that I removed the isset($post) check because you are running this code inside of foreach ( $postslist as $post ) which defines $post so it will always be set within that loop.
I also added the function sanitize_text_field() to sanitize the post_id. This is an important security measure to avoid SQL injection. All user input, including $_POST, can contain dangerous data and needs to be sanitized before use.
Hope this helps!
my form is unable to submit unless the checkbox is ticked, I am really unsure as to why this is.
further, if the checkbox is ticked it fails to update the database, there is no issue with the function I am using or the query as i have checked that directly on the db.
Any help would be hugely appreciated, and please feel free to ask any questions if there is anymore information i can give
<?php
include 'core/init.php';
protect_page();
include 'includes/overall/header.php';
$page = $_GET['page'];
$email = $_GET['user'];
$p_id = project_id_from_project_name($page);
$supervisor = supervisor_from_email($email, $p_id);
$user_id = user_id_from_email($email);
?>
<h1>Add A User to the Project</h1>
<?php
if (isset($_GET['form_submit']) === true && empty($_GET['form_submit']) === false) {
echo 'You\'re user has been added successfully!<br /><br />';
echo 'Please click here to return to Your Projects';
} else {
if (empty($_POST) === false && empty($errors) === true) {
$page = $_GET['page'];
$p_id = project_id_from_project_name($page);
$supervisor_update = ($_POST['supervisor'] == 1) ? 1 : 0;
$update_project_member_data = array(
'project_id' => "$p_id",
'project_name' => "$page",
'project_member_id' => "$user_id",
'supervisor' => "$supervisor_update"
);
update_project_member_data($p_id, $update_project_member_data);
header('Location: update_user.php?page=' . $page .'&user=' . $email .'&form_submit=1');
exit();
} else if (empty($errors) === false) {
echo output_errors($errors);
}
?>
<form action="" method="post">
<ul>
<li>
Email Address: <?php echo $email ?>
</li>
<li>
Set user as Supervisor?<br />
<input name="supervisor" type="checkbox" <?php if ($supervisor == 1) {?> checked="checked"<?php }?>/>
</li>
<li>
<input type="submit" value="Update User">
</li>
</ul>
</form>
<?php
}
include 'includes/overall/footer.php'; ?>
I believe the problem is with the condition you have:
empty($_POST) === false
Since your form is very basic and only has the one input. The $_POST array is only populated with values when that input is checked. Unchecked it doesn't pass any values in the $_POST array. Normally, the submit button would pass a value, but since you didn't have the "name" attribute on there, it doesn't.
You can either try adding the name attribute to the submit button or just add a hidden value inside the FORM element such as:
<input type="hidden" name="action" value="submitted" />
I think what is happening here is that there is no data to post if you do not check the box. You can check for the request method, $_SERVER['REQUEST_METHOD'] instead of empty($_POST).
edit: to clarify, the post happens but the if condition evaluates to false