How to modify default WordPress registration form? - php

I am creating one feature for adding user roles in WordPress default registration, it's working but I want to beautify it by adding a blank in user role selector, if it's showing a dropdown icon that will be awesome. I tried from my end but it's not showing.
My codes are: (enable 'anyone can register' here /wp-admin/options-general.php, to see the changes, now go to register /wp-login.php?action=register)
/*
show user profile in registeration
*/
//1. Add a new form element...
add_action('register_form', 'myplugin_register_form');
function myplugin_register_form()
{
global $wp_roles;
pll_e('Select Role');
echo '<select name="role" class="input">';
foreach ($wp_roles->roles as $key => $value) {
// Exclude default roles such as administrator etc. Add your own
if (!in_array($value['name'], ['Administrator', 'Editor'])) {
echo '<option value="' . $key . '">' . $value['name'] . '</option>';
}
}
echo '</select>';
}
//2. Add validation.
add_filter('registration_errors', 'myplugin_registration_errors', 10, 3);
function myplugin_registration_errors($errors, $sanitized_user_login, $user_email)
{
if (empty($_POST['role']) || !empty($_POST['role']) && trim($_POST['role']) == '') {
$errors->add('role_error', __('<strong>ERROR</strong>: You must include a role.', 'mydomain'));
}
return $errors;
}
//3. Finally, save our extra registration user meta.
add_action('user_register', 'myplugin_user_register');
function myplugin_user_register($user_id)
{
$user_id = wp_update_user(array('ID' => $user_id, 'role' => $_POST['role']));
}

Code is correct, change these lines from
echo '<select name="role" class="input">';
to
echo '<select name="role">';
this will give you a dropdown, without any conflict.
Now, these lines will give you a label
echo ('<label>Select Role</label>: ');
Paste this in your code, as per your need.
Learn inputs, form fields here https://www.w3schools.com/tags/tag_input.asp

Related

WordPress: Content in foreach remains on page because it does not refresh on form submission | Reload array after form submission?

I have tried the javascript refresh options on submit (on the <form> but none of them work. If I put the javascript refresh with the submit function, then every time it refreshes, the item gets sent to the database (do not want that).
What I have tried
onsubmit="location.reload()"
onsubmit="window.location.reload()"
onsubmit="setTimeout(function () { window.location.reload(); }, 10)"
It currently renders an array of items with a checkbox. When I click the checkbox, the item gets sent to the database as read -- but it stays on the screen (unless I revisit the page manually in the address bar). I am developing in WordPress using PHP.
Perhaps there is a small trick we can use just to remove the array that is sent on submit out of the books_array as soon as the submit button is clicked? Or reload the books_array after submission?
Here is my code:
form function
<form action="<?php user_add_new();?>" method="post">
<?php
foreach($books_array as $index => $i ) {
$s = $i->title;
$o = $i->listID;
$r = $i->submittedBy;
$d = $i->bookDESC;
$t = $i->id;
$current_user = wp_get_current_user();
$current_id = $current_user->ID;
if ($r == $current_user->ID || $r == 'administrator') {
echo '<div class="user-wrap">';
echo '<div class="inner-wrap">';
echo '<!---entire checkbox--->';
echo '<div><span class="check">';
echo "<input type='checkbox' name='checkbox[]' value='$index' onChange='this.form.submit()'>";
echo "<input type='hidden' name='item$index' value='$t'>";
echo "<input type='hidden' name='listID$index' value='$o'>";
echo "<input type='hidden' name='userID$index' value='$current_id'>";
echo '</span></div>';
echo '<!---entire checkbox--->';
echo '<!---info from book--->';
echo "<div><b>$s</b><br>$d</div>";
echo "<!---info from book--->";
echo '</div>';
echo '</div>';
}
};
?>
</form>
foreach loop
function user_add_new() {
global $wpdb;
$value = $_POST["checkbox"][0];
$bookTOadd = $_POST["item" . $value];
$listTOadd = $_POST["listID" . $value];
$userID = $_POST["userID" . $value];
$addTABLE = $wpdb->prefix . 'plugin_read';
$wpdb->insert(
$addTABLE,
array(
'bookID' => $bookTOadd,
'userID' => $userID,
'listID' => $listTOadd,
)
);
}
I keep running into issues, but I am so grateful to anyone who can give a little insight on how to approach this best. Thank you for taking the time to read this!
Problem fixed by creating a WordPress action and calling/rendering it only when the form is clicked (since before the action was rendered on page load just not executed until the click, which was 1 thing causing my issue re the not refreshing the entire page after form submission). No ajax (though its great with wordpress) nor .php files (that would just be a workaround).
Removed the action="" from my form, since we'll be using wordpress to do this.
Added this line <?php wp_nonce_field('book_send', 'book_send_nonce', true, true);?> to my form, you can see that below (this will help call my action in my WordPress file, associating it with this form)
<form method="post">
<?php wp_nonce_field('book_send', 'book_send_nonce', true, true);?>
<?php
foreach($books_array as $index => $i ) {
$s = $i->title;
$o = $i->listID;
$r = $i->submittedBy;
$d = $i->bookDESC;
$t = $i->id;
$current_user = wp_get_current_user();
$current_id = $current_user->ID;
if ($r == $current_user->ID || $r == 'administrator') {
echo '<div class="user-wrap">';
echo '<div class="inner-wrap">';
echo '<!---entire checkbox--->';
echo '<div><span class="check">';
echo "<input type='checkbox' name='checkbox[]' value='$index' onChange='this.form.submit()'>";
echo "<input type='hidden' name='item$index' value='$t'>";
echo "<input type='hidden' name='listID$index' value='$o'>";
echo "<input type='hidden' name='userID$index' value='$current_id'>";
echo '</span></div>';
echo '<!---entire checkbox--->';
echo '<!---info from book--->';
echo "<div><b>$s</b><br>$d</div>";
echo "<!---info from book--->";
echo '</div>';
echo '</div>';
}
};
?>
</form>
And this is my action (steps are described in the notes within the code) which makes the post when the action is called upon submit. It only submits the data after form validation. Once the data has been submitted, it then reloads the page using a built in WP function:
add_action('book_check', function() {
if ( ( is_single() || is_page() ) &&
isset($_POST[book_send_nonce]) &&
wp_verify_nonce($_POST[book_send_nonce], 'book_send')
) {
// form validation
function validate_book_data(){
$errors = new WP_Error();
if (isset($_POST[ 'item' ]) && $_POST[ 'item' ] !== '') {
$errors->add('item_error', 'Book not selected');
}
if (isset($_POST[ 'listID' ]) && $_POST[ 'listID' ] == '') {
$errors->add('list_error', 'No valid list this belongs to.');
}
if (isset($_POST[ 'userID' ]) && $_POST[ 'userID' ] == '') {
$errors->add('user_error', 'Not signed in');
}
return $errors;
}
// If form validation passes, send the info
$pass_validation = validate_book_data($_POST);
if ( $pass_validation ) {
$value = $_POST["checkbox"][0];
$data = array(
'userID' => $_POST["userID" . $value],
'bookID' => $_POST["item" . $value],
'list' => $_POST["listID" . $value],
);
global $wpdb;
// Select the table to post the data to
$book_checked = $wpdb->prefix . 'plugin_read';
// Insert the data to the table
$wpdb->insert($book_checked, $data, '%s');
// Set page refresh
$refresh_page = wp_redirect($_SERVER['HTTP_REFERER']);
// After data is inserted, refresh the page
wp_safe_redirect( $refresh_page );
// and exit
exit();
}
}
});
Using this action solves the issue of the page not refreshing because the action is only called when the checkmark is clicked and within the action, I refresh the page only after the data has sent.
I hope this will help anyone else with the issue. Coding from 8am-2am lately really had my brain become mush so the solution took me a short bit.

Why won't this form display properly from Wordpress shortcode?

<?php
/**
* Plugin Name: Display UserID
* Plugin URI: http://www.sitecrafters.pro/plugins/measurement-tracker.zip
* Description: The very seventh plugin that I have ever created.
* Version: 1.10
* Author: Cody King
* Author URI: http://sitecrafters.pro
*/
/**
* #snippet Display UserID
* #author Cody King
* #compatible Wordpress 6.0
*/
function show_form(){
$user_id = get_current_user_id();
echo '<form method="GET">'; // printing form tag
echo '<input type="text" name="inches">';
echo '<input type="submit" name="send_btn" value="Submit">';
echo '</form>';
if (isset($_GET['send_btn'])) { // checking is form was submitted then accessing to value
$bicep = $_GET['inches'];
if ($user_id == 0) {
// The user ID is 0, therefore the current user is not logged in
return; // escape this function, without making any changes to database
}
update_user_meta($user_id,'_bicep_measurement',$bicep);
return "Today your bicep is: $bicep inches!";
}
}
add_shortcode('show_form','show_form');
function checkBiceps(){
$user_id = get_current_user_id();
$bicep = get_user_meta($user_id,'_bicep_measurement',true);
return "Your bicep was: $bicep inches last time";
}
add_shortcode('check_biceps','checkBiceps');
?>
This is a plugin I'm making to track body part measurements for WordPress users. I have gotten the shortcode to work, and it makes a functional input box... Up in the top corner.
For some reason, this form is being displayed in the upper left corner instead of inline, where I put the shortcode. What am I doing wrong here?
I admit, I'm new to this programming language and making Wordpress plugins but I want to learn.
Like this:
<?php
function show_form()
{
$user_id = get_current_user_id();
$str = "";
$str .= '<form method="GET">'; // printing form tag
$str .= '<input type="text" name="inches">';
$str .= '<input type="submit" name="send_btn" value="Submit">';
$str .= '</form>';
if (isset($_GET['send_btn'])) { // checking is form was submitted then accessing to value
$bicep = $_GET['inches'];
if ($user_id == 0) {
// The user ID is 0, therefore the current user is not logged in
return; // escape this function, without making any changes to database
}
update_user_meta($user_id, '_bicep_measurement', $bicep);
return "Today your bicep is: $bicep inches!";
}
return $str;
}
add_shortcode('show_form', 'show_form');

Loop through form values from a dynamic php form

I building on top of an existing PHP based application to ability to update menu items name and prices.
I have generated a dynamic form which is populated with the results form the database. The idea is that the user can update the item name or price to update the information in the database.
The form works fine, but I am having dome trouble getting the info out of the form. each Item has a separate ID so I need to essentially do a foreach through the form and call the update function each time with the respective item id.
I can handle the DB side of things fine, but the application I am building on has a 'getInput' function to check input exists and to get the input form the form and I would like to use this.
This is the getInput function:
public static function exists($type = 'post') {
switch($type) {
case 'post':
return (!empty($_POST)) ? true : false;
break;
case 'get';
return (!empty($_GET)) ? true : false;
break;
default:
return false;
break;
}
}
public static function get($item) {
if(isset($_POST[$item])) {
return $_POST[$item];
} else if(isset($_GET[$item])) {
return $_GET[$item];
}
return '';
}
}
The problem I have is when calling this function it only returns the last item form the form. Is there a way i can iterate though the form and get each item?
This is the dynamic form and the getInput code so far:
$menuItems = DB::getInstance()->get('menu_items', array('cat_id', '=', $cat_id ));
if($menuItems->count()) {
echo '<form class="updateMenu" action="" method="post">';
echo '<table class="gridtable gridtableMenu">';
echo '<tr><th>Item Name</th><th>Item Price</th></tr>';
foreach($menuItems->results() as $item) {
echo '<tr>';
echo '<td class="menu-name"><input type="text" name="itemName" value="' . $item->item_name . '" required></td>';
echo '<td class="menu-price"><input type="number" step="any" name="itemPrice" value="' . $item->item_price . '" required></td>';
echo '<input type="hidden" name="id" value="' . $item->id . '">';
echo '</tr>';
}
echo '</table>';
echo '<input type="submit" name="updateMneu" value="Update Menu">';
echo '</form>';
} else {
echo '<div class="error">No items have been added to this menu</div>';
}
} // close categories foreach
} // close if category set
if(isset($_POST['updateMneu'])) {
echo Input::get('id'), '</br>';
echo Input::get('itemName'), '</br>';
echo Input::get('itemPrice'), '</br>';
} //close if isset updateMenu If
So I would like a foreach I think around this section:
if(isset($_POST['updateMneu'])) {
echo Input::get('id'), '</br>';
echo Input::get('itemName'), '</br>';
echo Input::get('itemPrice'), '</br>';
//update ite in the database, and move to gthe next item.
} //close if isset updateMenu If
I will handle data validation and what not later on.
As posted by 'noobHere' the answer was to set the input types name as arrays. e.g. name="itemName[]" instead of name="itemName"

get radio input value wordpress

I'm using a plugin which retrieves the value of some radio buttons based on what values I type in the plugin dashboard.
I want to change that function with a function which retrieves the post meta of a post as the value.
This is the function for retrieving the post meta :
<?php echo get_post_meta($post->ID, 'key', true); ?>
and this is the actual code for retrieving the values:
<?php
/* Radio form */
class ECF_Radio extends ECF_Field_Type {
protected $name = 'radio';
public function form_field( $ref, $field ) {
global $ecfdb;
$name = $ecfdb->html_string( $field->name );
echo "<div class='ecf-form-field-title'>$name</div>\n";
$values = preg_split( '/, ?/', $field->values );
echo '<div class=\'ecf-form-field-input\'>';
foreach ( $values as $i => $value ) {
$checked = checked( $i, 1, false );
echo "<p><label><input type='radio' name='$ref' "
. "value='$value'$checked /> $value</p></label>\n";
}
echo '</div>';
}
public function get_description() {
return "Radio selection field";
}
}
new ECF_Radio();
?>
My question is how can I use the function for retrieving the post meta for values?
What exactly do I need to change inside the code to retrieve the post meta not the values written in a filed.
Thank you!

Adding error with php in option list

Code below is part of cart66 WordPress plugin's php file. When I list options of my items for example,
T-shirt
Quantity: 1
Option: Red, Yellow, Blue
First option is always what I put first in the list. Therefore, when my customers don't pay an attention and add to cart without looking at the list they order red. I added "Please choose a pattern" option at the top but they still add that to cart and checkout. Is there a way of adding an option and making it give an error in case that option is selected ?
private function _buildOptionList($optNumber) {
$select = '';
$optionName = "options_$optNumber";
if(strlen($this->$optionName) > 1) {
$select = "\n<select name=\"options_$optNumber\" id=\"options_$optNumber\" class=\"cart66Options options_$optNumber\">";
$opts = split(',', $this->$optionName);
foreach($opts as $opt) {
$opt = str_replace('+$', '+ $', $opt);
$opt = trim($opt);
$optDisplay = str_replace('$', CART66_CURRENCY_SYMBOL, $opt);
$select .= "\n\t<option value=\"" . htmlentities($opt) . "\">$optDisplay</option>";
}
$select .= "\n</select>";
}
return $select;
}
You could use jQuery and Javascript to show an alert box.
<script type="text/javascript">
$(function() {
$('#options').change(function() {
if ($(this).attr('value') == "Please choose a pattern") {
alert("Please pick a color!");
}
});
});
</script>
Make sure to include a recent copy of jQuery in your page, and change the id="" value of the selectbox to options (without any PHP variable).
Also, don't forget to still check in PHP if the user submitted a valid color. Do this because if the user has Javascript disabled, he will still be able to choose the 'please choose a pattern' item.
That is a commercial plugin (albeit with a free "lite" version). I would first suggest checking out their support forums:
http://cart66.com/support/
If you don't mind editing the PHP yourself, then perhaps I can offer some suggestions.
E.g. you could have a blank option come first, then have the validation code reject adding the item to card when a blank item is selected. The code you pasted in looks like it takes a list of options as a comma-separated string. So you can have a blank option by starting the string with "," e.g. ",Red,Yellow,Blue". But that won't be very user-friendly, it would be better to have the first one named "Select Option" and have a value of "". Since the above code does not allow this, you could alter that code, e.g. like this:
private function _buildOptionList($optNumber) {
$select = '';
$optionName = "options_$optNumber";
if(strlen($this->$optionName) > 1) {
$select = "\n<select name=\"options_$optNumber\" id=\"options_$optNumber\" class=\"cart66Options options_$optNumber\">";
$opts = split(',', $this->$optionName);
foreach($opts as $opt) {
if($opt == "<blank>") {
$opt = "";
$optDisplay = "Select One";
} else {
$opt = str_replace('+$', '+ $', $opt);
$opt = trim($opt);
$optDisplay = str_replace('$', CART66_CURRENCY_SYMBOL, $opt);
}
$select .= "\n\t<option value=\"" . htmlentities($opt) . "\">$optDisplay</option>";
}
$select .= "\n</select>";
}
return $select;
}
Then you could have your options list be ",Red,Yellow,Blue".
You may also need to modify cart66's verification code to make sure it rejects blank selections. I don't know if it does just by looking at the above code snippet.
There are a few ways to do this. Most simply, using plain Javascript, add this to the <form> element: <form onsubmit="if ( this.options_1.selectedIndex() == 0 ) { alert( 'Please select a colour' ); return false; >
(options_1 will need to match the $optNumber used to generate the drop-down. The return false; will prevent the form from submitting)
You could use jQuery to make this neater and more flexible; for instance, give your options a special value like "_NOT_SELECTED_", and use something like
<script type="text/javascript">
jQuery(function($) {
$('form.cart66Form').bind('submit', function()
{
$('select.cart66Options').each( function()
{
if ( $(this).val() == '_NOT_SELECTED_' )
{
$('#incorrect_submission_message').show();
return false;
}
}
return true;
}
});
</script>
Finally, of course, validation is always better done on the server side, in this case meaning in the PHP, so you'll need to find where the "add to basket" action happens in the plugin (or where you can add some actions to it) and add something that checks if your special value ("_NOT_SELECTED_", or perhaps just "-") has been submitted.

Categories